更新:送信時にフォーム要素に追加されるように追加されたselectタグにname属性を追加することにより、この問題を修正しました。
getが外部キーを持つモデルを渡すという部分的なビューがあります。部分ビューの唯一の目的は、このモデルのデータベースに新しいオブジェクトを作成することです。モデルの外部に基づいてフィールドの1つにドロップダウンを作成しましたが、フォームを投稿すると、そのフィールドはレコードを作成するための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>
フォーム送信時にストアフィールドをモデルの一部にするにはどうすればよいですか?送信をオーバーライドして、knockoutjsビューモデルの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; }