ASP.NET MVC Model Binding into a List

こ雲淡風輕ζ 提交于 2019-12-12 07:06:51

问题


In my ASP.NET MVC site, part of a feature allows the user to enter the hours when a certain venue is open.

I've decided to store these hours in a VenueHours table in my database, with a FK-to-PK relationship to a Venues table, as well as DayOfWeek, OpeningTime, and ClosingTime parameters.

In my View, I want to allow the user to only input the times they know about; in other words, some days may not be filled in for a Venue. I'm thinking of creating checkboxes that the user can check to enable the OpeningTime and ClosingTime fields for the DayOfWeek that the checkbox belongs to.


My question relates to how to pass this information to my HttpPost Controller Action.

As I know the maximum amount of Days that can be passed in (7), I could of course just write 7 nullable VenueHour parameters into my Action, but I'm sure there's a better way.

Can I somehow bind the View information into a List that is passed to my Action? This will also help me if I run into a scenario where there is no limit to how much information the user can fill in.


回答1:


Scott Hanselman posted a very good article about how the default model binder deals with collections, arrays and dictionaries. It's great if you don't want to write a custom model binder, although writing a custom model binder isn't that big a deal.




回答2:


Please try the following steps

1 - Place all the input boxes (which can be populated by DatePicker JQuery control) inside a div in the aspx view.

2 - using Jquery selectors to capture all the values(inside the above specified DIV) that needs to be posted to the Action method , into a JavaScript array in the Client Side.

please refer Filtering input elements inside DIV

var enteredVenueHours = new Array();
for(var i=0;i < inputsInsideDiv.length;i++)
{
    // add the elements to the JS array
}

3 - Use the Jquery post to send the enteredVenueHours back to the controller action**

$.post('<%=Url.Action("ActionMethod")%>',{ EnteredVenueHours: enteredVenueHours,function (data)
{
     // Udpate status to be displayed here. 
});

4 - Make sure the Controller action method has the following Signature

[AcceptVerbs(HTTP.Post)]
public ActionResult ActionMethod(List<string> EnteredVenueHours)
{
     // Have the DB persistance logic .
}


来源:https://stackoverflow.com/questions/3058632/asp-net-mvc-model-binding-into-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!