我使用了扩展方法并编写了一个下拉列表,现在我想从视图中获取所选值并传递给控制器。怎么办?
public static MvcHtmlString DayDropDownCalender(this HtmlHelper helper)
{
TagBuilder daydropdown = new TagBuilder("select");
for (int i = 1; i <= 31; ++i)
{
var option = new TagBuilder("option");
option.SetInnerText(i.ToString());
option.MergeAttribute("value", i.ToString());
daydropdown.InnerHtml += option.ToString();
}
return MvcHtmlString.Create(daydropdown.ToString(TagRenderMode.Normal));
}
答案 0 :(得分:1)
您应该为<select>
元素提供name
属性:
TagBuilder daydropdown = new TagBuilder("select");
daydropdown.Attributes["name"] = "day";
然后您的[HttpPost]
控制器操作可以简单地将其作为参数:
[HttpPost]
public ActionResult Index(string day)
{
... the day parameter will contain the selected value
}
或者如果您想要将多个简单标量值传递给控制器操作,您只需设计一个包含所需信息的视图模型:
public class MyViewModel
{
public string Day { get; set; }
public string Month { get; set; }
public string Year { get; set; }
...
}
您的控制器操作将采取:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
...
}