[英]Submit multiple radio button values with one button ASP.NET MVC
我的頁面上有三組單選按鈕,我想用一個按鈕提交它們的每個值。
<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個單選按鈕[name,value]對發送給操作? 另外,所有三個組的形式是否應相同或分開?
我願意使用javascript,但更喜歡使用Razor HTML幫助器。
謝謝
模型
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;
}
}
控制者
[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();
}
視圖
@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
將持有包含提交值的字典
您可以使用FormCollection門控您的帖子上的單選按鈕值。
您只需編寫var variable = f [“ rating1”]; 在您的發布方法中,您會在發布方法中獲得所選的單選按鈕值,
public ActionResult Rate(Guid uniqueId,FormCollection f)
{
var variable1 = f["rating1"];
var variable2 = f["rating2"];
var variable3 = f["rating3"];
[...]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.