gpt4 book ai didi

c# - MVC 4 Dropdownlist 通过按钮传递值?

转载 作者:行者123 更新时间:2023-11-30 20:41:38 25 4
gpt4 key购买 nike

我使用 html 助手创建了一个下拉列表。它能够获取值并绑定(bind)到下拉列表。

如何将选定的下拉值传递给 Controller ​​?

我的看法:

@Html.DropDownList("Language", new SelectList(ViewBag.LangList, "Text", "Value"))
<input type="button" class="btn" title="Filter By Language"
value="Filter By Language" onclick="location.href='@Url.Action("SURV_Answer_Result", "SURV_Answer",
new { Survey_ID = Model[0].Survey_ID, Language = ViewBag.LangList })'" />

我的 Controller 获取语言并绑定(bind)到下拉列表中:

public ActionResult SURV_GetLanguage(int Survey_ID)
{
var getlanguagelist = from r in db.SURV_Question_Ext_Model
join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID
where s.Question_Survey_ID == Survey_ID
group new { r, s } by r.Qext_Language into grp
select grp.FirstOrDefault();

foreach (var item in getlanguagelist.ToList())
{
List<SelectListItem> langResult = new List<SelectListItem>();
foreach (var item2 in getlanguagelist)
{
SelectListItem temp = new SelectListItem();
temp.Text = item2.r.Qext_Language;
temp.Value = item2.r.Qext_Language;
langResult.Add(temp);
}
ViewBag.LangList = langResult;
}
return View(ViewBag.Langlist) ;
}

我想将语言传递给下面的 Controller :

 public ActionResult SURV_Answer_Result(int Survey_ID, string Language)
{
List<AnswerQuestionViewModel> viewmodel = new List<AnswerQuestionViewModel>();
SURV_GetLanguage(Survey_ID);
// do whatever i want...
}

最佳答案

View 中的按钮是 type="button"你附上了一个onclick将重定向到 SURV_Answer_Result 的事件路过原文ViewBag属性返回到方法(它不会绑定(bind)到 string Language 因为它是 List<SelectListItem>

您需要一个带有 FormMethod.Get 的表格

@using (Html.BeginForm("SURV_GetLanguage", "ControllerName", new { Survey_ID = Model[0].Survey_ID }, FormMethod.Get))
{
@Html.DropDownList("Language", (Enumerable<SelectListItem>)ViewBag.LangList)
<input type="submit" ... />
}

注意事项:

  1. Survey_ID已作为路由值添加到表单中
  2. ViewBag.LangListEnumerable<SelectListItem>这就是全部DropDownList() 需要 helper 所以没有意义创建另一个 SelectList 的额外开销从中( SelectListEnumerable<SelectListItem> )

关于c# - MVC 4 Dropdownlist 通过按钮传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32200747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com