3

我有一个动作方法 Rate() 的 HttpPost 和 HttpGet 版本:

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 方法,我的想法是提交按钮标签中的值“模型”将是这样做的参数,但是如果我传递 null Post 方法内部的断点。for 循环试图创建 5 个按钮来发送正确的评分。

谢谢

4

2 回答 2

5

它们的模型绑定适用于name属性,因为@Ragesh 建议您需要指定与RatingModel视图中的属性匹配的名称属性。另请注意,提交按钮值不会发布到服务器,您可以通过一些技巧来实现这一点,一种方法是包含一个隐藏字段。

同样在您提供的代码中,循环运行六次,最后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");
    }

希望你能明白

于 2012-03-12T05:37:35.140 回答
0

我认为您需要解决两件事:

  1. input标签需要一个name属性
  2. name属性应设置为model.Rating
于 2012-03-12T02:20:18.480 回答