[英]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.