C# 来自数据库的 ASP.NET MVC 下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18613851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC dropdown-list from database
提问by Tobias
Ok, so I'm new to this whole MVC-world, but it seems to be a pretty good way of getting things done and I'm trying to make it work here.
好的,所以我是整个 MVC 世界的新手,但这似乎是完成工作的一种很好的方式,我正在努力让它在这里工作。
The problem is: I can't get data from my table in my SQL-database to a simple drop-down form on my registration page.
问题是:我无法从我的 SQL 数据库中的表中获取数据到我的注册页面上的简单下拉表单。
I have just no idea where to put the stuff, where to code to open the table, select the ids, where to put the response.write
and how do I send it to the view?
我只是不知道把东西放在哪里,在哪里编码以打开表格,选择 ID,在哪里放置response.write
以及如何将它发送到视图?
My Model is this:
我的模型是这样的:
public class users
{
public string name {get; set;}
public int user_id {get; set;}
}
My Controller is this:
我的控制器是这样的:
[HttpGet]
public ActionResult ListUser()
{
return View();
}
And my View is this:
我的观点是这样的:
@model Community.Models.users
I have googled for 2 days now and watched several videos on youtube but of no use, I can't find it. Please, anyone with some knowledge here? And please point me to some good tutorials and/or forums where I can browse for more questions I might have
我已经用谷歌搜索了 2 天,并在 youtube 上观看了几个视频,但没有用,我找不到。请问这里有懂行的吗?请给我指点一些好的教程和/或论坛,我可以在那里浏览更多我可能遇到的问题
Still no luck on this project..
这个项目仍然没有运气..
I'm creating a form and within that form, i want a db-loop (IEnumerable
).. But the current model is not a IEnumerable
. I'm pretty much stuck, watched a bunch of tutorials and they all just list ONE connection, what if I want two models?
我正在创建一个表单,在该表单中,我想要一个 db-loop ( IEnumerable
.. 但当前模型不是IEnumerable
. 我几乎卡住了,看了一堆教程,他们都只列出一个连接,如果我想要两个模型怎么办?
Here is my Controller, I get that you must pass a list to the view, right?
这是我的控制器,我知道您必须将列表传递给视图,对吗?
public ActionResult Registration()
{
return View(db.users.ToList());
}
How do i get hold of that list in my view witout an IEnumerable
model?
如何在没有IEnumerable
模型的情况下在我的视图中获得该列表?
@neoistheone, your example didnt help me much, my DB opens like this:
@neoistheone,你的例子对我没有多大帮助,我的数据库是这样打开的:
private DataBaseContext db = new DataBaseContext();
and i don't know how, but it opens the connection. I've tried for so many hours now, its just silly, haven't slept for soo long!
我不知道如何,但它打开了连接。我已经尝试了这么多小时了,它只是很傻,很久没睡了!
I'm used to programming ASP-Classic fyi, and this is my first serious try to upgrade my knowledge about programing an up-to-date language and OOP.
我习惯于编程 ASP-Classic fyi,这是我第一次认真尝试升级我关于编程最新语言和 OOP 的知识。
回答by Mike Perrenoud
Add the SelectList
to your model:
添加SelectList
到您的模型:
public SelectList DropDownList { get; set; }
build the class for that collection:
为该集合构建类:
public class MyListTable
{
public string Key { get; set; }
public string Display { get; set; }
}
and then in your controller, load the data for the MyListTable
class from the database:
然后在您的控制器中,MyListTable
从数据库加载该类的数据:
var list = new List<MyListTable>();
using (SqlConnection c = new SqlConnection(cString))
using (SqlCommand cmd = new SqlCommand("SELECT KeyField, DisplayField FROM Table", c))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
list.Add(new MyListTable
{
Key = rdr.GetString(0),
Display = rdr.GetString(1)
});
}
}
}
var model = new users();
model.DropDownList = new SelectList(list, "Key", "Display");
and then finally, you need to send your model to the view:
最后,您需要将模型发送到视图:
return View(model);
Now in the Razor you can display this:
现在在 Razor 中,您可以显示:
@Html.DropDownListFor(m => Model.DropDownList);
You of course can name these things better names, but you get the idea.
你当然可以给这些东西命名更好的名字,但你明白了。
回答by Jeet Bhatt
Try this,
尝试这个,
model
模型
public string CoutryID { get; set; }
public List<SelectListItem> CountryList { get; set; }
Controller method which fill the list
填充列表的控制器方法
public List<Country> getCountryList()
{
using (QRMG_VendorPortalDataContext _context = new QRMG_VendorPortalDataContext())
{
return (from c in _context.Countries
where c.IsDeleted == false
select c).ToList();
}
}
Drop down list in View
视图中的下拉列表
@Html.DropDownListFor(m => m.CoutryID,
new SelectList(Model.CountryList,
"CoutryID", "Value"))
回答by Tobias
If you are really new to ASP.Net MVC, this is a quite good Tutorial that shows you how the MVC-Pattern works.
如果你真的是 ASP.Net MVC 的新手,这是一个很好的教程,它向你展示了 MVC 模式是如何工作的。
MVC3: http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3
MVC4: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
MVC3:http: //www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3
MVC4:http: //www.asp.net/mvc /教程/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4
Here is the sample-code to download: http://code.msdn.microsoft.com/Introduction-to-MVC-3-10d1b098
这是要下载的示例代码:http: //code.msdn.microsoft.com/Introduction-to-MVC-3-10d1b098
this is an helpful video: http://www.asp.net/mvc/videos/mvc-1/conference-presentations/creating-nerddinnercom-with-microsoft-aspnet-model-view-controller-mvc
这是一个有用的视频:http: //www.asp.net/mvc/videos/mvc-1/conference-presentations/creating-nerddinnercom-with-microsoft-aspnet-model-view-controller-mvc
回答by Basheer AL-MOMANI
this is my table in the database
这是我在数据库中的表
take look it my Action controller
看看我的动作控制器
// GET: Letters
public ActionResult Index()
{
ViewBag.LetterStatus = new SelectList(LetterStatusService.GetAllLettersStatus(), "Id", (CultureHelper.GetCurrentCulture() == "ar") ? "NameArabic" : "Name", Request.QueryString["LetterStatus"]);
return View();
}
and in the view
并且在视图中
@Html.DropDownList("LetterStatus")
the constructor I used is
我使用的构造函数是
new SelectList(
list<Objlect> myListFromDatabase,
string PropertyNameOfValueInHtml,
string PropertyNameOfDesplayInHtml,
string SelectedItemValue
);
this line Request.QueryString["LetterStatus"]
because I send the Selected Items within QuerySrting
这条线Request.QueryString["LetterStatus"]
是因为我将选定的项目发送到QuerySrting
and based on CurrentCulture
I chose what column to display
并基于CurrentCulture
我选择要显示的列
but I think the best way to do this,,,, is to get or create the Items then Iterate throw them to generate the select tag manually. I described this approach well in this answer
但我认为最好的方法是获取或创建项目,然后迭代抛出它们以手动生成选择标签。我在这个答案中很好地描述了这种方法
hope this helps you
希望这对你有帮助
回答by aim
There a great answers already but Here is another approach.
已经有很好的答案,但这是另一种方法。
You will use user
as a model, ListUserViewModel
as view-model and UserController
as the contoller. The work of view-model is to carry all info needed to be displayed on the page from the controller without adding unwanted properties into the model class. In your case list of users from database into the drop down list.
您将user
用作模型、ListUserViewModel
视图模型和UserController
控制器。view-model 的工作是从控制器携带所有需要在页面上显示的信息,而不会将不需要的属性添加到模型类中。在您的情况下,将数据库中的用户列表放入下拉列表。
Model:
模型:
public class User //By the way use singular when naming a class
{
public string name {get; set;}
public int user_id {get; set;}
}
View-model
视图模型
public class ListUserViewModel
{
public list<User> Users{get; set;}
}
Controller
控制器
public class UserController : Controller
{
private DataBaseContext db = new DataBaseContext();
[HttpGet]
public ActionResult ListUser()
{
var users = db.Users.ToList();
var viewModel = new ListUserViewModel { Users = users };
return View(viewModel);
}
}
Now use ListUserViewModel instead of User in your view as a model
现在在您的视图中使用 ListUserViewModel 而不是 User 作为模型
@model Community.Models.ListUserViewModel
and the drop down
和下拉
@Html.DropDownListFor(m => m.Users, new SelectList(Model.Users, "user_id", "name"), " ")
Explanation:
解释:
You are creating drop down list for Users with Model.Users
as select list data source. "user_id"
as a value of the selected user and "name"
as display label. the last argument( i put empty string " "
) is a default value that the drop down will display before selection.
您正在使用Model.Users
选择列表数据源为用户创建下拉列表。"user_id"
作为所选用户的值和"name"
显示标签。最后一个参数(我把空字符串" "
)是一个默认值,下拉菜单将在选择之前显示。
I hope this will help you or someone else.
我希望这会帮助你或其他人。
回答by RickL
I find this system works (and avoids using ViewBag):
我发现这个系统有效(并避免使用 ViewBag):
View Model:
查看型号:
public class YourViewModel
{
// This could be string, int or Guid depending on what you need as the value
public int YourDropdownSelectedValue { get; set; }
public IEnumerable<SelectListItem> YourDropdownList { get; set; }
}
Controller:
控制器:
// Get database values (by whatever selection method is appropriate)
var dbValues = db.YourEntity.ToList();
// Make Selectlist, which is IEnumerable<SelectListItem>
var yourDropdownList = new SelectList(dbValues.Select(item => new SelectListItem
{
Text = item.YourSelectedDbText,
Value = item.YourSelectedDbValue
}).ToList(), "Value", "Text");
// Assign the Selectlist to the View Model
var viewModel = new YourViewModel(){
// Optional: if you want a pre-selected value - remove this for no pre-selected value
YourDropdownSelectedValue = dbValues.FirstOrDefault(),
// The Dropdownlist values
YourDropdownList = yourDropdownList
};
// return View with View Model
return View(viewModel);
and in the View:
并在视图中:
@Html.DropDownListFor(a => a.YourDropdownSelectedValue, Model.YourDropdownList, "select this text - change this to null to exclude", new { @class = "your-class" })