Sending model to mvc3 using html.beginform

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

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 returned by HttpGet Rate ():

@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 am trying to find out how to submit a model via a form to the Post method and I thought the value "model" in the submit button tag would be a parameter for this, however null is passed through if I breakpoint inside the Post method. The for loop tries to create 5 buttons to send the correct rating.

thank

+3


source to share


2 answers


Them model binding works with attribute name

as @Ragesh suggested that you need to specify name attributes to match properties RatingModel

in the view. Also note that the submit button values ​​are not sent to the server, there are hacks through which you can achieve this, one way is to enable the hidden field.

Also in your provided code the loop is executed six times and at the end it Model.Rating

will 5

always equal ... what are you trying to achieve ?. Let's 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 get an idea

+5


source


I think you need to fix two things:



  • Tag input

    needs an attributename

  • The attribute name

    must be set tomodel.Rating

0


source







All Articles