2012-03-12 71 views
3

发送在MVC3模型我有动作方法速率()的HttpPost和HTTPGET版本:使用html.beginform

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速率()返回的视图:

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

感谢

+0

HTTP:/ /stackoverflow.com/editing-help#code – SLaks 2012-03-12 01:47:22

+0

pastebin链接不是SO上的代码块的好替代品。 – 2012-03-12 01:50:41

回答

0

我认为有两件事情你需要修复:

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

他们的模型绑定对name属性起作用,因为@Ragesh建议您需要指定fy与视图中的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"); 
    } 

希望你能得到的想法