sending a model in mvc3 using html.beginform

Josh Monks picture Josh Monks · Mar 12, 2012 · Viewed 28.8k times · Source

I have an HttpPost and HttpGet version of the action method Rate() :

http://pastebin.com/embed_js.php?i=6x0kTdK0

    public ActionResult Rate(User user, Classified classified)
    {
        var model = new RatingModel
                {
                    CurrentUser = user,
                    RatedClassified = classified,                        
                };
        return View(model);
    }
    [HttpPost]
    public ActionResult Rate(RatingModel model)
    {
        model.RatedClassified.AddRating(model.CurrentUser, model.Rating);
        return RedirectToAction("List");
    }

The view that HttpGet Rate() returns:

@model WebUI.Models.RatingModel
@{
    ViewBag.Title = "Rate";
}
Rate @Model.RatedClassified.Title
@using(Html.BeginForm("Rate","Classified", FormMethod.Post))
{
    for (int i = 1; i < 6; i++)
    {
        Model.Rating = i;
        <input type="submit" value="@i" model="@Model"></input>
    }
} 

I'm trying to find out to send a Model through the Form to the Post method, and my thinking was that the value "model" in the submit button's tag would be the parameter to do so, however null is being passed through if i breakpoint inside of the Post method. The for loop is trying to create 5 buttons to send the proper rating.

Thanks

Answer

JIA picture JIA · Mar 12, 2012

Them model binding works on the name attribute as @Ragesh suggested you need to specify the name attributes matching the RatingModel properties in the view. Also note that the submit button values dont get posted to the server, there are hacks through which you can achieve that, one way is to include a hidden field.

Also in your provided code the loop runs six times and at the end Model.Rating will be equal to 5 always... what are you trying to achieve?. Say for example you have a model like

public class MyRating{

 public string foo{get;set;}

 }

in your view

@using(Html.BeginForm("Rate","Classified", FormMethod.Post))

 @Html.TextBoxFor(x=>x.foo) //use html helpers to render the markup
 <input type="submit" value="Submit"/>
}

now your controller will look like

[HttpPost]
    public ActionResult Rate(MyRating model)
    {
        model.foo // will have what ever you supplied in the view
        //return RedirectToAction("List");
    }

hope you will get the idea