使用HTML.BeginForm在MVC3中发送模型

3

我有一个HttpPost和HttpGet版本的操作方法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");
    }

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>
    }
} 

我正在尝试通过表单将模型发送到Post方法,并且我的想法是提交按钮标记中的值“model”将是实现此目的的参数,但是如果我在Post方法内设置断点,则传递null。for循环正在尝试创建5个按钮以发送正确的评分。

谢谢


http://stackoverflow.com/editing-help#code - SLaks
在SO上,pastebin链接不是代码块的好替代品。 - M.Babcock
2个回答

5

模型绑定是基于name属性的,正如@Ragesh所建议的那样,您需要在视图中指定与RatingModel属性匹配的name属性。还请注意,提交按钮的值不会被发送到服务器,有一些技巧可以实现这一点,其中一种方法是包含一个隐藏字段。

此外,在您提供的代码中,循环运行六次,最后Model.Rating始终等于5...你想要实现什么?例如,假设您有一个模型:

public class MyRating{

 public string foo{get;set;}

 }

在您看来
@using(Html.BeginForm("Rate","Classified", FormMethod.Post))

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

现在你的控制器将会变成这样

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

希望您能理解这个概念。


0

我认为你需要修复两个问题:

  1. input标签需要一个name属性
  2. name属性应该设置为model.Rating

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接