在表单提交后更新控制器中的部分视图模型值

时间:2014-03-24 13:30:11

标签: asp.net-mvc controller model-binding asp.net-mvc-partialview form-post

在我的示例MVC应用程序中,我有一个模型

class SampleModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Certification> Certifications { get; set; }
}

class Certification
{
    public int Id { get; set; }
    public string CertificationName { get; set; }
    public int DurationInMonths { get; set; }
}

我的观点(我需要在部分视图中显示认证详细信息)

@model SampleApplication.Model.SampleModel
<!-- other code... -->
@using (Html.BeginForm("SaveValues","Sample", FormMethod.Post, new { id= "saveForm" }))
{
    @Html.HiddenFor(m => m.Id, new { id = "hdnID" }) 
    @Html.TextBoxFor(m => m.Name, new { id = "txtName" })
    @{Html.RenderPartial("_CertDetails.cshtml", Model.Certifications);}
    <input type="submit" id="btnSubmit" name="btnSubmit" value="Update"  />
}

部分视图

@model List<SampleApplication.Model.Certification>
<!-- other code... -->
@if (@Model != null)
{
    for (int i = 0; i < @Model.Count; i++)
    {
        @Html.HiddenFor(m => m[i].Id , new { id = "CId" + i.ToString() })
        @Html.TextBoxFor(m => m[i].CertificationName,new{ id ="CName" + i.ToString() })
        @Html.TextBoxFor(m => m[i].DurationInMonths,new{ id ="CDur" + i.ToString() })
    }
}

控制器

[HttpPost]
public ActionResult SaveValues(SampleModel sm)
{
    //Here i am not getting the updated Certification details (in sm)
}

如何在表单发布后获取控制器中部分视图的更新值?当我不使用partialview时,我能够获得更新的认证值。 这是正确的方式,还是应该遵循其他方法?

2 个答案:

答案 0 :(得分:2)

如果sm.Certifications返回null,则表示没有发布任何内容,或者模型绑定器无法正确附加发布的数据。

在您的部分中,您正在使用索引器正确定义字段,但最初,Certifications是一个空列表,因此实际上从未运行此代码。这意味着,在其他地方你有一些JavaScript逻辑,它动态地向页面添加新的Certification字段,我的猜测是JavaScript生成的字段名称​​不遵循索引约定模型绑定器所期望的。您的所有字段都应采用以下格式:

ListProperty[index].PropertyName

因此,在您的情况下,您的JS应该生成如下名称:

Certifications[0].CertificationName

为了正确绑定数据。

答案 1 :(得分:1)

哦,Nooo ......这是我的错误:(。我将认证列表作为我的部分视图模型

 @model List<SampleApplication.Model.Certification>

但我也应该在局部视图中使用相同的模型(主页面模型)。

 @model SampleApp.Models.SampleModel  

在局部视图中,编码将类似于

        @for (int i = 0; i < @Model.Certifications.Count; i++)
        {
            @Html.HiddenFor(m => m.Certifications[i].Id, new { id = "CId" + i.ToString() })
            @Html.TextBoxFor(m => m.Certifications[i].CertificationName, new { id = "CName" + i.ToString() })
            @Html.TextBoxFor(m => m.Certifications[i].DurationInMonths, new { id = "CDur" + i.ToString() })<br /><br />
        }

现在我在控制器中获取更新的值。

感谢@Chris Pratt提示。