我有一个下拉列表中的项目列表,该列表是从" ASP.NET Identity"," aspnetusers"中的自定义属性创建的。表名为" FullName"。我的目标是从下拉列表中选择名称,并在我的"应用程序"中保存全名和ID。表创建一对多关系。下拉列表中填充了名称,但不会将它们保存到我的应用程序表中。
型号:
public class HomeController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public class Application
{
public int ApplicationId { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
*****Asp.net identity application user class that I have a custom full name property in*****
public virtual ApplicationUser ApplicationUser { get; set; }
}
控制器:
public ActionResult Index()
{
ViewBag.LoanOfficer = new SelectList(db.Users,"Id","FullName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "Id,FullName,FirstName,LastName")] Application application)
{
if (ModelState.IsValid)
{
ViewBag.LoanOfficer = new SelectList(db.Users, "Id", "FullName", application.ApplicationUser);
db.Applications.Add(application);
db.SaveChanges();
return RedirectToAction("Thanks");
}
return View(application);
}
查看:
@Html.DropDownList("LoanOfficer", "Select Loan Officer")
答案 0 :(得分:2)
您的模型没有名为LoanOfficer
的属性,因此无法绑定。如果您检查Request.Form
,则会看到所选ID
的{{1}}值,因此您需要在保存前将其手动添加到User
。但是你的代码存在很多问题,包括你使用Application
的方式,@Html.DropDownList()
的无意义使用(你列出所有3个属性,但无论如何它们都是默认绑定的,你已经包含了" FullName"它甚至不是模型的属性),如果模型有效,则重新创建[Bind(Include="...")]
(这是没有意义的,因为您立即重定向,但如果您返回则不会创建它view - 这意味着下拉列表中不会显示任何内容)
创建视图模型以表示您要显示和编辑的内容
SelectList
控制器
public class ApplicationVM
{
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required]
[DisplayName("Loan officer")]
public int? LoanOfficer { get; set; }
public SelectList LoanOfficerList { get; set; }
}
查看
public ActionResult Create()
{
ApplicationVM model = new ApplicationVM();
model.LoanOfficerList = new SelectList(db.Users, "Id", "FullName");
return View();
}
[HttpPost]
public ActionResult Create(ApplicationVM model)
{
if(!ModelState.IsValid)
{
model.LoanOfficerList = new SelectList(db.Users, "Id", "FullName");
return View(model);
}
// Initialize new Application, set properties from the view model, save and redirect
}