我的页面上有三组单选按钮,我想用一个按钮提交每个值。
<table>
<tr>
<td>
@Html.RadioButton("rating1", "yes", true) Yes
@Html.RadioButton("rating1", "no", false) No
@Html.RadioButton("rating1", "maybe", false) Maybe
</td>
</tr>
<tr>
<td>
@Html.RadioButton("rating2", "yes", true) Yes
@Html.RadioButton("rating2", "no", false) No
@Html.RadioButton("rating2", "maybe", false) Maybe
</td>
</tr>
<tr>
<td>
@Html.RadioButton("rating3", "yes", true) Yes
@Html.RadioButton("rating3", "no", false) No
@Html.RadioButton("rating3", "maybe", false) Maybe
</td>
</tr>
</table>
我想将字典作为参数发送到控制器操作,以便我可以检索每个评级的值。
控制器如下所示:
public ActionResult Rate(Guid uniqueId, Dictionary<Guid, string> ratings)
{
[...]
}
我试过了:
<input type="submit" value="Send Ratings" onclick="@Url.Action("Rate", "Controller", new {new Dictionary<string,string> {{"rating1", "yes"}, {"rating2", "no"}, {"rating3", "maybe"}})"></input>
但不允许将Dictionary作为RouteValue传递。
如何使用一个按钮/提交将所有3个单选按钮[名称,值]对发送到操作?此外,所有三个小组是否应采用相同的形式或单独的形式?
我愿意使用javascript,但更喜欢使用Razor HTML帮助程序。
由于
答案 0 :(得分:0)
Model
public class ExampleViewModel
{
public ExampleViewModel()
{
Answers = new Dictionary<string, string>();
Questions = new List<KeyValuePair<string, List<string>>>();
}
public Dictionary<string, string> Answers { get; set; }
public List<KeyValuePair<string, List<string>>> Questions { get; set; }
public ExampleViewModel Add(string key, string[] value)
{
Questions.Add(new KeyValuePair<string, List<string>>(key, value.ToList()));
return this;
}
}
Controller
[HttpGet]
public ActionResult Index()
{
ExampleViewModel model = new ExampleViewModel();
model.Add("rating1",new[] { "Yes" ,"No", "Maybe"});
model.Add("rating2", new[] { "Yes", "No", "Maybe" });
model.Add("rating3", new[] { "Yes", "No", "Maybe" });
return View(model);
}
[HttpPost]
public ActionResult Index(ExampleViewModel model)
{
//model.Answers is the dictionary of the values submitted
string s = model.Answers.Count.ToString();
return View();
}
View
@model ExampleViewModel
@using (Html.BeginForm())
{
<table class="table table-bordered table-striped">
@for(int i=0;i<Model.Questions.Count;i++)
{
var question = Model.Questions[i];
<tr>
<td>
@foreach (var answer in question.Value)
{
<input type="hidden" name="Model.Answers[@question.Key].Key" value="@question.Key" />
<input type="hidden" name="Model.Answers.Index" value="@question.Key" />
@Html.RadioButton("Model.Answers[" + question.Key+"].Value", answer, false) @answer
}
</td>
</tr>
}
<tr>
<td>
<input type="submit" class="btn btn-primary" value="Submit" />
</td>
</tr>
</table>
}
model.Answers
will hold the dictionary containing the submitted values
答案 1 :(得分:-1)
您可以使用FormCollection选择帖子上的单选按钮值。
你必须在post方法中简单地写 var variable = f [“rating1”]; ,并在post方法中获得所选的单选按钮值,
public ActionResult Rate(Guid uniqueId,FormCollection f)
{
var variable1 = f["rating1"];
var variable2 = f["rating2"];
var variable3 = f["rating3"];
[...]
}