将生成的字段绑定到剃刀视图中进行建模

时间:2013-01-01 01:39:04

标签: c# asp.net-mvc razor knockout.js

更新:通过将name属性添加到已添加的select标记来修复此问题,以便在提交时将其添加到formelement。

我有一个部分视图,即获取传递具有外键的模型。局部视图的唯一目的是在数据库中为此模型创建一个新对象。我根据模型之外的内容为其中一个字段创建了一个下拉列表,现在当我发布表单时,该字段不包含在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>

如何在表单提交中将Store字段作为模型的一部分?我重写了提交以在knockoutjs视图模型中调用createContactFromForm函数。

更新了正在调用的viewmodel的一部分:

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; }

1 个答案:

答案 0 :(得分:0)

所以我想出了如何将'new'字段添加到正在提交的模型中。我必须给这篇文章创作,让我朝着正确的方向前进。 DynamicallyAddedForm,这是此问题的链接stack link

我已更新代码以显示通过提交传递的添加的HTML属性。归结为命名约定并确保它与模型匹配。