2017-02-23 23 views
0

當我有以下形式:只對多個對象提交選定的複選框的MVC控制器

<input type="checkbox" name="modules" value="1" /> 
<input type="checkbox" name="modules" value="2" /> 
<input type="checkbox" name="modules" value="3" /> 

此西港島線正確地發送到以下MVC控制器:

[HttpPost] 
public ActionResult Submit(string[] modules) 
{ 

} 

但上面的時候是什麼表單被包裝成for循環,如下所示:

@for (int i = 0; i < cart.Events.Count; i++) 
{ 
    <h1>@cart.Events[i].Name</h1> 
    <input type="checkbox" name="modules" value="1" /> 
    <input type="checkbox" name="modules" value="2" /> 
    <input type="checkbox" name="modules" value="3" /> 
} 

使用看起來像t他的:

[HttpPost] 
public ActionResult Submit(TestObject modules) 
{ 

} 

public class TestObject 
{ 
    public string[] modules { get; set; } 
} 

這將無法正常工作,因爲MVC不知道如何將表單數據綁定到對象。我只想發送選定的值,因爲並不是說模塊複選框的計數總是相同的。

如何解決這個問題?

+0

你的模型需要一個屬性說'布爾IsSelected'和值的屬性,說'的int Value' - 參見[這個答案](http://stackoverflow.com/questions/29542107/pass-list-of- checkboxes-in-view-and-pull-out -enumerable/29554416#29554416)舉例 –

+0

你也可以添加TestObject的代碼 – Usman

回答

0

所有的複選框具有相同的名稱,你可以自定義由名:@( 「模塊」 + cart.Events [I],請將.Name)。