2010-09-01 59 views
1

我試圖將checkboxes的值保存在查詢字符串中的同名表單(level和coursetype)中,以便我可以檢查哪些被選中。在第一次提交時,我得到:在MVC中處理複選框的最佳方式

Search?coursetype=1416&coursetype=post16&level=3&level=6&level=1 

這很好,所以我可以檢查值返回到視圖中並勾選先前選擇的值。

然而,當我使用pagedList或Html.ActionLink,例如:

Html.ActionLink("search again", "Search", new { coursetype = ViewData["coursetype"], level = ViewData["level"]}) 

我得到:Search?&coursetype=System.String%5B%5D&level=System.String%5B%5D

我試圖從陣列中解析這些值,但後來當我送他們到htmlAttributes在ActionLink中,我得到:Search?coursetype%3D1416&coursetype%3Dpost16&level%3D3&level%3D6&level%3D1,所以視圖無法找到複選框的值。

控制器:

[AcceptVerbs("GET")] 
public ActionResult Search(string[] coursetype, string[] level) 
{ 
    ViewData["level"] = level; 
    ViewData["coursetype"] = coursetype; 

    return View(); 
} 
+0

原始ViewData如何設置? – 2010-09-01 22:10:45

+0

從一組複選框填充 – 2010-09-02 07:48:30

回答

1

您是否使用強類型搜索視圖?

我想你會想要使用ViewModel在你的視圖和控制器之間傳遞數據。

public class CourseViewModel 
{ 
    public string Level { get; set; } 
    public string CourseType { get; set; } 
} 

那麼你的看法是強類型的CourseViewModel所以你可以建立你的ActionLink的是這樣的:

Html.ActionLink("search again", "Search", new { coursetype = Model.CourseType, level = Model.Level }) 

而且您的控制器是這樣的:

[AcceptVerbs("GET")] 
public ActionResult Search(string coursetype, string level) 
{ 
    var viewModel = new CourseViewModel 
    { 
     CourseType = coursetype, 
     Level = level 
    }; 

    return View(viewModel); 
} 

希望這幫助。我不確定這是您尋找的內容,但如果您有任何問題,請告訴我!

+0

我推薦這種方法,因爲它是強類型和易於使用。我在我的所有ASP.NET MVC項目中使用自定義ViewModels。 – 2010-09-01 22:05:59

+0

我可以這樣做,但如果模型屬性是一個字符串,不知道是否會解決我的問題[] – 2010-09-02 07:50:22

+0

您的模型是您的視圖模型。在我的例子中,它將是CourseViewModel。這兩個屬性都是字符串,由您來設置視圖模型類的屬性的類型。我重讀了你的問題,看起來你有一堆複選框而不是文本框?如果您在窗體上使用複選框,則需要將這些複選框映射到視圖模型上的布爾屬性,併爲每個複選框設置可選的布爾參數。 – 2010-09-02 14:08:48

0

ViewData["..."]object類型。你想一起把它作爲string[]類型,所以你必須做出一個小的變化:

相反的:

Html.ActionLink("search again", "Search", new { coursetype = ViewData["coursetype"], level = ViewData["level"]}) 

嘗試:

Html.ActionLink("search again", "Search", new { coursetype = ViewData["coursetype"] as string[], level = ViewData["level"] as string[] }) 

我說的唯一的事情就是as string[]之後ViewData["..."]

希望有幫助!

+0

感謝您的回答Maxim,但我得到了相同的結果:一個字符串包含「System.String []」 – 2010-09-01 14:58:09