为什么我的@Html.DropDownListFor()中没有显示正确的值
本文关键字:显示 @Html 我的 DropDownListFor 为什么 | 更新日期: 2023-09-27 18:24:37
我是.NET MVC的初学者,正在尝试执行一项简单的任务,例如在下拉列表中显示项目列表。然而,我当前的代码会生成一个下拉列表,显示项目类型的名称,而不是实际值。谢谢你帮忙。:)
DropDown未显示正确的值
我的代码如下;
选择ArticleModel.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; }
}
}
条款.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);
}
}
}
索引.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>
让SelectList
知道Value和Text属性的名称。
@Html.DropDownListFor(m => m.Name,
new SelectList(Model.Articles, "Name", "Name", Model.Name)))
由于使用复杂对象进行绑定,因此可以将dataTextField和dataValueField指定为SelectList
的参数。尝试以下操作:
@Html.DropDownListFor(m => m.Name, new SelectList(Model.Articles,"Name","Name"))
如果您有一个基元类型(如字符串)的列表,那么您正在使用的SelectList
的重载将在不提及额外参数的情况下工作。