这些是我的POCO课程:
public class PollOptions
{
public int Id { get; set; }
public virtual Polls Polls { get; set; }
public string Answer { get; set; }
public int Votes { get; set; }
}
public class Polls
{
public int Id { get; set; }
public string Question { get; set; }
public bool Active { get; set; }
public virtual ICollection<PollOptions> PollOptions { get; set; }
}
我将这个模型传递给了Index视图:
public ActionResult Index()
{
var poll = db.Polls.Include("PollOptions").Where(x => x.Active).ToList();
return View(model);
}
并在索引视图中我希望用户投票及以下 是我的民意调查部分:
@section Polling{
@foreach (var question in Model.Polls)
{
<h3>@question.Question</h3>
<ul class="pollUnordedList">
@foreach(var answer in question.PollOptions)
{
<li><input type="radio" name="opt" id="@answer.Id" value="1"/><span>@answer.Answer</span></li>
}
</ul>
}
@using (Html.BeginForm(actionName: "Radio", controllerName: "Home",routeValues: new { id = 2, value = 5 }))
{
<p><input type="submit" class="btn btn-primary" value="ارسال نظر" /></p>
}
}
我的行动方法:
public void Radio(int Id=0,int value=0)
{
PollOptions opt = db.PollOptions.Find(Id);
db.Entry(opt).State = System.Data.EntityState.Modified;
opt.Votes += value;
db.SaveChanges();
}
如何获取radioButton的值和id作为路由值传递,例如在上面的路由中,Id和值的值为2.5
答案 0 :(得分:1)
我使用jQuery AJAX解决了我的问题:
@using (Html.BeginForm(actionName: "Radio", controllerName: "Home")) {
foreach (var question in Model.Polls)
{
<h3>@question.Question</h3>
<ul class="pollUnordedList">
@foreach (var answer in question.PollOptions)
{
<li>
@*@Html.RadioButton("options",false,new {id=@answer.Id})<span>@answer.Answer</span>*@
@Html.RadioButton("options",answer.Id)<span>@answer.Answer</span>
</li>
}
</ul>
}
<p>
<input type="submit" id="btnVote" class="btn btn-primary" value="ارسال نظر" />
</p>
}
和我的行动方法:
[HttpPost]
public ActionResult Radio(int options)
{
var option = db.PollOptions.Find(options);
if (option != null) option.Votes++;
db.SaveChanges();
return RedirectToAction("Index");
}
感谢Daniel Liuzzi,不需要foreach,因为如果选中单选按钮,则会在发布表单时提交单选按钮的值。
答案 1 :(得分:0)
为所有单选按钮使用相同的名称:
@using (Html.BeginForm(actionName: "Radio", controllerName: "Home")) {
foreach (var question in Model.Polls) {
<h3>@question.Question</h3>
foreach (var answer in question.PollOptions) {
<label>
<input type="radio" name="answers" value="@answer.Id" />
@answer.Answer
</label>
}
}
<p><input type="submit" class="btn btn-primary" value="ارسال نظر" /></p>
}
然后在您的操作方法上,您将选择的答案作为数组接收:
[HttpPost]
public ActionResult Radio(int[] answers)
{
// TODO: Save your answers
}
修改强>
根据你关于价值总是等于1的评论,那么传递它是没有意义的。您只需为每个选定的单选按钮假设值为1。您的操作方法看起来像这样:
[HttpPost]
public ActionResult Radio(int[] answers)
{
foreach (var id in answers)
{
var option = db.PollOptions.Find(id);
if (option != null) option.Votes++;
db.SaveChanges();
}
}