.Net MVC3中的下拉列表 [英] DropDown in .Net MVC3
本文介绍了.Net MVC3中的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的MVC Web应用程序中创建一个dropdonw.
I am trying to create a dropdonw in my MVC web application.
型号
namespace projectname.Models
{
public class DropDownModel
{
public int id{get; set;}
puclic string value {get; set;}
}
}
控制器
using projectname.Models;
{
public class DropDownController: Controller
{
public ActionResult Index() //where Index is one of the view
{
List <SelectListItem> listItem = new List<SelectListItem>();
DropDownModel drop = new DropDownModel();
drop.id = 1;
drop.value = "First";
listItem.Add(new SelectListItem() {Value = drop.Value, Text = drop.id.toString()});
return view(listitem);
}
}
}
查看
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
但是,该下拉列表没有显示在我的索引视图中.
However, the drop down is not being displayed on my Index view.
推荐答案
在MVC中有几种显示DropDownList的方法.这是我的方式.
There are a few ways of display DropDownList in MVC. Here is my way.
注意:您需要模型中的 SelectListItem 集合.
public class MyModel
{
public int SelectedId { get; set; }
public IList<SelectListItem> AllItems { get; set; }
public MyModel()
{
AllItems = new List<SelectListItem>();
}
}
控制器
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel();
model.AllItems = new List<SelectListItem>
{
new SelectListItem { Text = "One", Value = "1"},
new SelectListItem { Text = "Two", Value = "2"},
new SelectListItem { Text = "Three", Value = "3"}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Get the selected value
int id = model.SelectedId;
return View();
}
}
查看
@model DemoMvc.Controllers.MyModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownListFor(x => x.SelectedId, Model.AllItems)
<input type="submit" value="Submit" />
}
这篇关于.Net MVC3中的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文