我是.NET MVC的初学者,并尝试执行一项简单的任务,例如在下拉列表中显示项目列表。但是,我当前的代码会生成一个下拉列表,显示项目类型的名称而不是实际值。谢谢你的帮助。 :)
DropDown not displaying the correct values
我的代码如下;
SelectArticleModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TheMakingOfAWebApplication.Models
{
public class SelectArticleModel
{
public string Name { get; set; }
public IEnumerable<Article> Articles { get; set; }
}
}
Article.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TheMakingOfAWebApplication.Models
{
public class Article
{
public string Name { get; set; }
}
}
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TheMakingOfAWebApplication.Models;
namespace TheMakingOfAWebApplication.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//List<Article> articles;
SelectArticleModel model = new SelectArticleModel();
model.Name = "";
model.Articles = new List<Article>{
new Article { Name = "Bananas"},
new Article { Name = "Apples"},
new Article { Name = "Oranges"},
new Article { Name = "Melons"},
new Article { Name = "Grapes"},
new Article { Name = "Sallad"},
new Article { Name = "Potatoes"},
new Article { Name = "Cucumber"},
new Article { Name = "Beans"},
new Article { Name = "Tomatoes"}
};
return View(model);
}
}
}
Index.cshtml
@model TheMakingOfAWebApplication.Models.SelectArticleModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Article</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Name, new SelectList(Model.Articles)))
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
答案 0 :(得分:2)
让您的SelectList
知道Value和Text属性名称是什么。
@Html.DropDownListFor(m => m.Name,
new SelectList(Model.Articles, "Name", "Name", Model.Name)))
答案 1 :(得分:0)
由于您使用复杂对象进行绑定,因此可以将dataTextField和dataValueField指定为SelectList
的参数。请尝试以下方法:
@Html.DropDownListFor(m => m.Name, new SelectList(Model.Articles,"Name","Name"))
如果你有一个像字符串这样的基本类型的列表,那么你正在使用的SelectList
的重载可以在不提及额外参数的情况下工作。