[英]Bind generated fields to model in razor view
更新:通過將name屬性添加到選擇的標簽中,以便在提交時將其添加到表單中,解決了此問題。
我有一個局部視圖,它可以通過具有外鍵的模型。 局部視圖的唯一目的是在數據庫中為此模型創建一個新對象。 我根據模型之外的內容為其中一個字段創建了一個下拉列表,現在我發布表單時,該字段未包含在api帖子中以創建記錄。 (對於那些熟悉的人,是的,這幾乎是開箱即用的聯系示例,我正在嘗試對其進行擴展,並可以使用一些幫助)
<form id="addContact" data-bind="submit: createContactFromForm">
@Html.ValidationSummary(true)
<fieldset>
<legend>Contact</legend>
@Html.EditorForModel()
<div class="editor-label"><label>Store:</label></div>
<div class="editor-field" id="storediv">
<select id="StoreId" **name="StoreId"** data-bind="options: stores, optionsText: 'Name', optionsValue: 'Id', optionsCaption: 'Choose...'"></select>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
</form>
如何獲得“商店”字段作為表單提交模型的一部分? 我重寫提交以在基因敲除js視圖模型中調用createContactFromForm函數。
更新了被稱為的視圖模型部分:
self.createContactFromForm = function (formElement) {
// If valid, post the serialized form data to the web api
$(formElement).validate();
if ($(formElement).valid()) {
$.post("api/contacts", $(formElement).serialize(), "json")
.done(function (newContact) {
self.contacts.push(newContact);
$('#addContact')[0].reset();
});
}
}
服務器端模型:
public Contact()
{
this.Created = DateTime.Now;
this.Emails = new List<Emails>();
}
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required, MaxLength(256)]
public string FirstName { get; set; }
[Required, MaxLength(256)]
public string LastName { get; set; }
[ScaffoldColumn(false)]
public string Name { get { return string.Concat(this.FirstName, " ", this.LastName); } set { } }
[MaxLength(256)]
public string EmailAddress {
get
{
return this.Emails.Count == 0 ? string.Empty : this.Emails[0].EmailAddress;
}
set
{
if (this.Emails.Count == 0)
{
this.Emails.Add(new Emails());
}
this.Emails[0].EmailAddress = value;
}
}
[MaxLength(50)]
public string PhoneNumber { get; set; }
[MaxLength(256)]
public string Address { get; set; }
[MaxLength(256)]
public string City { get; set; }
[MaxLength(50)]
public string State { get; set; }
[MaxLength(256)]
public string ZipCode { get; set; }
[Required]
[ScaffoldColumn(false)]
public int StoreId { get; set; }
public Store Store { get; set; }
[ScaffoldColumn(false)]
public DateTime Created { get; set; }
public virtual IList<Emails> Emails { get; protected set; }
因此,我想出了如何向正在提交的模型中添加“新”字段。 我必須創造這篇文章,這使我朝着正確的方向前進。 DynamicallyAddedForm ,它是此問題堆棧鏈接中的鏈接
我已經更新了代碼,以顯示與提交一起傳遞的添加的HTML屬性。 歸結為命名約定,並確保它與模型匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.