我试图将RadioButtonFor传递给模型。
控制器
[HttpPost]
public ActionResult Contact(ApplicationCommentType model)
{
//send email here
//reload form
ApplicationCommentType appdata = new ApplicationCommentType();
appdata.CommentTypeData = db.CommentTypes.ToList();
return View(appdata);
}
ApplicationCommentType
public class ApplicationCommentType
{
public IEnumerable<CommentType> CommentTypeData { get; set; }
public String CommentTypeDataSelection { get; set; }
public String Name { get; set; }
public String Email { get; set; }
public String Comment { get; set; }
}
CommentType
public partial class CommentType
{
public int CommentTypeID { get; set; }
public string CommentTypeDesc { get; set; }
}
查看
@using(@Html.BeginForm("Contact", "Home", FormMethod.Post, new{ @class ="form-horizontal"})){
<fieldset>
<legend>Contact Us</legend>
<div class="form-group">
@Html.LabelFor(x => x.Email, new {@class="col-lg-2 control-label"})
<div class="col-lg-10">
@Html.TextBoxFor(x => x.Email, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(x => x.Name, new { @class = "col-lg-2 control-label" })
<div class="col-lg-10">
@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<label for="textArea" class="col-lg-2 control-label">Questions, Comments, or Concerns</label>
<div class="col-lg-10">
@Html.TextAreaFor(x => x.Comment, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Comment Type</label>
<div class="col-lg-10">
@foreach (var item in Model.CommentTypeData)
{
<div class="radio">
<label>
@Html.RadioButtonFor(x => x.CommentTypeData, item.CommentTypeDesc)
@Html.LabelFor(m => m.CommentTypeData, item.CommentTypeDesc, item.CommentTypeID)
</label>
</div>
}
@Html.HiddenFor(x => x.CommentTypeDataSelection)
</div>
</div>
</fieldset>
}
现在这种作品,所有文本框项目都有效。在[HttpPost]
返回上放置断点会产生以下值。
Comment: "awesome"
CommentTypeData: Count = 0
CommentTypeDataSelection: null
Email: "example@example.com"
Name: "John Smith"
不应该注释CommentTypeData有计数吗?如果我检查请求,那么选择的值就在那里。
Request.Params["CommentTypeData"]: "General Improvement Suggestion"
那为什么模型没有更新?是否需要从Request对象手动更新Model?
答案 0 :(得分:0)
您可以使用@ Html.RadioButtonFor,但您应确保 item.CommentTypeDesc 与Radio类型兼容。
请参阅MVC4: Two radio buttons for a single boolean model property
希望它有所帮助。