开发者

Best way of handle checkboxes in MVC

I'm trying to keep the values of checkboxes in a form with the same name (level and coursetype) in the querystring so I can check which ones were selected. In the first submit, I get:

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

which is f开发者_如何学运维ine so I can check the values back into the view and tick the ones previously selected.

However, when I use a pagedList or Html.ActionLink, for example:

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

I get: Search?&coursetype=System.String%5B%5D&level=System.String%5B%5D

I tried parsing those values from the array but then when I send them to htmlAttributes in the ActionLink I get: Search?coursetype%3D1416&coursetype%3Dpost16&level%3D3&level%3D6&level%3D1 so the view can't find the values of the checkbox.

Controller:

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

   return View();
}


Are you using a strongly-typed Search view?

I would think you would want to use a ViewModel to pass the data between your view and controller.

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

Then your view would be strongly typed to the CourseViewModel so you could construct your ActionLink like this:

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

And your controller would look like this:

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

   return View(viewModel);
}

Hopefully this helps. I'm not sure if this is what your looking for, but let me know if you have any questions!


ViewData["..."] is of type object. You want to pass it along as type string[], so you have to make a small change:

Instead of:

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

Try:

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

The only thing I added was as string[] after ViewData["..."].

Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜