0

I have a Fairly Complex Form that I need to post to my MVC controller.

Here is the View model which I initially pass to the view on creation:

public class EditViewModel
{
    public Service service { get; set; }
    public bool sms { get; set; }
    public bool email { get; set; }
    public string userId { get; set; }
}

Here is my View (simplified):

@model IList<Service_Monitor_Web_Interface.Models.ViewModels.EditViewModel>
@{
  ViewBag.Title = "Configure User Notifications";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("Edit", "Users", FormMethod.Post, new { @class = "stdform stdform2", role = "form" }))
{
@Html.AntiForgeryToken()
<hr />

<p>
    <label><u> Service:</u> </label>
    <span class="field">
        <u>Notification Methods:</u>
    </span>
</p>


for (int i = 0; i < Model.Count; i++)
{
    <p>
        <label>@Model[i].service.Name</label>
        <span class="field">
            @Html.CheckBoxFor(model => model[i].sms)
            SMS &nbsp;&nbsp;
            @Html.CheckBoxFor(model => model[i].email)
            Email &nbsp;&nbsp;
        </span>
    </p>
}
<br clear="all" /><br />

<p class="stdformbutton">
    <button class="submit radius2">Save</button>
    <input type="reset" class="reset radius2" value="Reset Form" />
</p>
}

And here is my Action method in my controller:

    //
    // POST: /Users/Edit
    [HttpPost]
    public ActionResult Edit(IList<EditViewModel> viewModel)
    {
        return View(viewModel);
    }

How Can I bind my view model when receiving it on the controller? Currently when I debug the action method receives a ViewModel which looks like so:

enter image description here

How can I get service and userId not to be null?

4

1 回答 1

2

请注意,在您的助手的 lambdas 中,正式地说model => service.sms右侧部分 ( service.sms) 不是从左侧部分 ( model) 派生的。这会导致name结果输入的所有属性都相同,并为您提供您不期望的请求参数。

标准做法是在循环情况下使用forinstaed of 。foreach这样就可以正确生成生成的 html 的名称属性:

for(int i=0; i<Model.Count; i++)
{
    <p>
        <label>@Model[i].service.Name</label>
        <span class="field">                
            @Html.CheckBoxFor(model => model[i].sms)
            SMS &nbsp;&nbsp;               
            @Html.CheckBoxFor(model => model[i].email)
            Email &nbsp;&nbsp;
        </span>
    </p>
}

请注意,这需要Model是实现类型IList而不是IEnumerable.

更新。对于其他没有任何 UI 的值,您可以使用隐藏字段,这样它们对用户不可见,但仍会发布到服务器:

<label>@Model[i].service.Name</label>
<span class="field">                
    @Html.CheckBoxFor(model => model[i].sms)
    SMS &nbsp;&nbsp;               
    @Html.CheckBoxFor(model => model[i].email)
    Email &nbsp;&nbsp;
    @Html.HiddenFor(mode => model[i].userId)
    @Html.HiddenFor(mode => model[i].service.Name)
    ...other field of service you want to be posted...
</span>
于 2014-02-25T12:13:23.510 回答