2011-06-17 69 views
1

如何從剃鬚刀視圖引擎中動態創建的複選框列表中查找複選框的值(即,是否已選中)?代碼運行如下...要從剃鬚刀視圖引擎中動態創建的複選框列表中獲取複選框的值

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

如何獲取控制器中的這些複選框值?

回答

1

正確的做法:使用視圖模型和編輯器模板。

由於總是通過定義視圖模型開始:

public class MyViewModel 
{ 
    public string Title { get; set; } 
    public string Id { get; set; } 
    public bool IsThreshold { get; set; } 
} 

然後控制器,用於填充此視圖模型:

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

然後Index視圖(~/Views/Home/Index.cshtml):

@model IEnumerable<MyViewModel> 

<table> 
    <thead> 
     <tr> 
      <th></th> 
      <th>Threshold</th> 
     </tr> 
    </thead> 
    <tbody> 
     @Html.EditorForModel() 
    </tbody> 
</table> 

最後編輯模板(~/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>