Asp.net mvc: custom ViewModel form post

We just start with ASP.NET MVC and are already facing a stumbling block.

The situation is that I have a custom ViewModel to navigate to a view that contains a list of elements that will be rated (jQuery star rating will be used), so they are created using the radio button helper to have the same name, just another value, and it does not pose a problem.

I have absolutely no idea how to actually get this back to the post version of my action. I just get the "no parametric constructor" error. I do not want to use a collection of forms - I want my data to remain based on classes.

Did anyone have to do something like this?

Thanks so much for any advice.

==================================================== =======================

UPDATE (main code included):

    In the HomeController:

    public class MyViewModel 
    {
        public MyViewModel(List<Thing> things ) // Thing.cs contains properties name and rating
        {
            this.Things = things;           
        }

        public List<Thing> Things { get; private set; }
    }


   public ActionResult Index()
   {
        List<Thing> things = new List<Thing>();

        Thing t;

        t = new Thing();
        t.name = "One";
        t.rating = 1;
        things.Add(t);

        t = new Thing();
        t.name = "Two";
        t.rating = 2;
        things.Add(t);

        return View(new MyViewModel(things));  
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Index( MyViewModel vm)
    {
        return View();
    }       

    and in the Index page ( Inherits="System.Web.Mvc.ViewPage<MyProject.Controllers.MyViewModel>" )

 <% using (Html.BeginForm())
   {%>
    <ul>
    <%  for( int t = 0; t<Model.Things.Count; t++)
        {%>
            <li>
                <% for (int i = 1; i < 6; i++)
                   {
                       MyProject.Thing thing = Model.Things[i];
                       %>
               <%=Html.RadioButton(String.Format("Things[{0}]", t), i)%>
                   <% } %>

            </li>
    <%  }%>
    </ul>    
    <input type="submit" value="submit me" />
<% } %>               
+3
source share
2 answers

Try using a parameterless constructor for the ViewModel. In addition, property names must match the names / identifiers of controls.

You may need to simplify a little or even write your own connecting device.

Explanation of model binders and their use here .

A good article on writing a model binder here .

, , . , , , .

!

+3

, .

UpdateModel() , .

0

Source: https://habr.com/ru/post/1714069/


All Articles