使用MVC中的model和storedprocedure绑定下拉列表 [英] Binding drop down list using model and storedprocedure in MVC
问题描述
我是MVC应用程序的新手,我在网络表单方面有很好的经验。请举例说明使用模型和存储过程绑定下拉列表,这意味着使用ADO。 MVC中的网络。
我创建了与以下URL相同的Employee项目。
C#Corner [ ^ ]
我想添加人物标题,如先生,夫人等,以及
城市名称,如金奈,班加罗尔等。
请帮帮我。
I am new to MVC application and I have good experience in web forms. please give some examples to bind dropdown list using Models and Stored procedure which means using ADO. Net in MVC.
I have created Employee project same as from the below URL.
C# Corner[^]
I would like to add Person Title such as Mr, Mrs, etc. and
City Name such as Chennai, Bangalore, etc.
Please help me out.
推荐答案
你可以在Viewbag的帮助下完成。我们假设您将不同的标题存储在名为TitleTable的数据库表中。
使用ADO.Net从TitleTable获取所有标题并创建一个SelectListItem列表,如:(假设您知道如何连接到数据库并获取数据)
You can do this with the help of Viewbag. Let us say you have the different titles stored in a database table called TitleTable.
Use ADO.Net to get all the titles from TitleTable and create a list of SelectListItem like:(assuming you know how to connect to DB and get data)
titleList = (from titleRow in dtTitle.AsEnumerable()
select new SelectListItem()
{
Selected = false,
Text = resRow["Title"].ToString(),
Value = resRow["Title"].ToString()
}).ToList();
上面的代码使用数据表,但你可以使用数据集或datareader。
要从create视图访问此titleList,请将其放入ViewBag中。必须在将用户发送到创建视图之前(在创建控制器操作方法中返回View()语句之前)完成此操作。
Above code uses datatable, but you can use dataset or datareader.
In order to access this titleList from create view, put this into a ViewBag. This has to be done before the user is sent to the create view (before return View() statement in the Create controller action method).
ViewBag.Titles = titleList;
现在,您可以在视图中使用此ViewBag来填充下拉列表。在此之前为Person添加一个新属性,例如:
Now you can use this ViewBag in your view to populate the dropdown list. Before that add a new property to the model you have for Person, like:
public string PersonTitle {get; set;}
在视图中添加Title的控件并使用ViewBag填充它。以下是示例代码:
And in the view add control for Title and populate it with ViewBag. Here is the sample code:
<div class="form-group">
@Html.LabelFor(model => model.Year, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.PersonTitle, new SelectList(@ViewBag.Titles, "Value", "Text"), "--Select Title--")
@Html.ValidationMessageFor(model => model.Titles)
</div>
</div>
希望这会有所帮助。
Hope this helps.
这篇关于使用MVC中的model和storedprocedure绑定下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!