如何在mvc 3.0中绑定dropdownlist [英] How to bind dropdownlist in mvc 3.0
问题描述
亲爱的先生,
我是mvc的新手,我想在MVC 3.0中绑定dropdownlist。我的代码如下:
table
tbl_Modules
Module_Id ,ModuleName,ModuleDescription
tbl_DocumentTypes
Document_Id,DocumentName,DocumentDescription, Module_Id
现在我想要在表单中添加文档类型并在表单中我想要一个下载列表,其中Module_Id为值,ModuleName为文本。
Dear Sir,
I am new in mvc and i want to bind dropdownlist in MVC 3.0. My Code is given below
tables
tbl_Modules
Module_Id,ModuleName,ModuleDescription
tbl_DocumentTypes
Document_Id,DocumentName,DocumentDescription,Module_Id
now i want to craete form to add document type and in form i want a dropdownlist with Module_Id as value,ModuleName as text.
public class DocumetRepository
{
InwardManagementEntities db = new InwardManagementEntities();
public IQueryable<tbl_DocumentTypes> FindAllDocumentTypes()
{
return db.tbl_DocumentTypes;
}
}
public class DocumentTypeViewModel
{
ModuleRepository _modulerepository = new ModuleRepository();
public tbl_DocumentTypes Document { get; private set; }
public SelectList Modules { get; private set; }
public DocumentTypeViewModel(tbl_DocumentTypes document)
{
Document = document;
//var _modules = _modulerepository.FindAllModules().Select(d => new {Module_Id= SqlFunctions.StringConvert((double?)d.Module_Id), Text = d.ModuleName });
var _modules = _modulerepository.FindAllModules().Select(d => new SelectListItem() {Value= SqlFunctions.StringConvert((double?)d.Module_Id), Text = d.ModuleName });
Modules = new SelectList(_modules, Document.Module_Id);
}
}
和conroller
And in conroller
public ActionResult AddDocument()
{
tbl_DocumentTypes _document = new tbl_DocumentTypes();
return View(new DocumentTypeViewModel(_document));
}
并且在视图中
and in view
<div class="editor-label">
Module
</div>
<div class="editor-field">
@Html.DropDownList("Document.Module_Id", Model.Modules.ToList())
@Html.ValidationMessageFor(model => model.Document.Module_Id)
</div>
但是在下拉列表中我得到System.Web.Mvc.SelectListItem 。请帮助我
but in dropdownlist i get System.Web.Mvc.SelectListItem . Please help me
推荐答案
Maneesh你正在使用@ Html.DropDownList而不是@Html.DropDownListFor帮助器。看看这篇文章
mvc 3中的绑定下拉列表 [ ^ ]
Maneesh you are using @Html.DropDownList instead of @Html.DropDownListFor helper. Look into this article
Binding drop down list in mvc 3[^]
请阅读下面提到的关于如何使用dropdwonlist绑定viewmodel的文章。
示例代码:
Please read below mentioned article which I have written about how to bind viewmodel with dropdwonlist.
sample code :
@Html.DropDownListFor(m => m.SelectedValue,new SelectList(Model.ProductCategories, "Id","CategoryName"),"-Please select a category -")
这篇关于如何在mvc 3.0中绑定dropdownlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!