To get the value of check boxes from a list of dynamicallly created check boxes in razor view engine
How to find the values of checkboxes(i.e., whether checked or not) from a list of dynamically created check boxes in razor view engine? the code runs as follows...
@foreach (var item in Model))
{
       <tr>
          <td class="Viewtd">
              @Html.ActionLink(item.Title, "Edit", new { id = item.id})
          </td>开发者_开发问答
          <td>
     @Html.CheckBox("ChkBox"+item.ThresholdID , false, new { id = item.id})                         
          </td>
       </tr>
}
How to get those check boxes values in the controller?
Do it the proper way: using view models and editor templates.
As always start by defining a view model:
public class MyViewModel
{
    public string Title { get; set; }
    public string Id { get; set; }
    public bool IsThreshold { get; set; }
}
then a controller to populate this view model :
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[] 
        {
            new MyViewModel 
            {
                Id = "1",
                Title = "title 1",
                IsThreshold = false,
            },
            new MyViewModel 
            {
                Id = "2",
                Title = "title 2",
                IsThreshold = true,
            },
            new MyViewModel 
            {
                Id = "3",
                Title = "title 3",
                IsThreshold = false,
            },
        };
        return View(model);
    }
    [HttpPost]
    public ActionResult Edit(MyViewModel model)
    {
        // This action will be responsible for editing a single row
        // it will be passed the id of the model and the value of the checkbox
        // So here you can process them and return some view
        return Content("thanks for updating", "text/plain");
    }
}
and then the Index view (~/Views/Home/Index.cshtml):
@model IEnumerable<MyViewModel>
<table>
    <thead>
        <tr>
            <th></th>
            <th>Threshold</th>
        </tr>
    </thead>
    <tbody>
        @Html.EditorForModel()
    </tbody>
</table>
and finally the editor template (~/Views/Home/EditorTemplates/MyViewModel.cshtml):
@model MyViewModel
@{
    ViewData.TemplateInfo.HtmlFieldPrefix = "";
}
<tr>
    @using (Html.BeginForm("Edit", "Home"))
    {
        @Html.HiddenFor(x => x.Id)
        @Html.HiddenFor(x => x.Title)
        <td><input type="submit" value="@Model.Title" /></td>
        <td>@Html.CheckBoxFor(x => x.IsThreshold)</td>
    }
</tr>
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论