aspnetusers 表中的 ViewBag 下拉列表在发布时未保存到数据库



我有一个下拉列表中的项目列表,该列表是从名为"FullName"的"ASP.NET Identity","aspnetusers"表中的自定义属性创建的。 我的目标是从下拉列表中选择名称,并将全名和 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")

模型没有名为 LoanOfficer 的属性,因此无法绑定。如果检查Request.Form,您将看到所选UserID值,因此您需要在保存之前手动将其添加到Application。但是你的代码有很多问题,包括你使用@Html.DropDownList()的方式,[Bind(Include="...")]的毫无意义的使用(你列出了所有 3 个属性,但无论如何它们都是默认绑定的,并且你已经包含了"FullName",它甚至不是模型的属性),以及你重新创建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
}

视图

@model ApplicationVM
@using(Html.BeginForm())
{
  ....
  // controls for FirstName and LastName properties
  @Html.LabelFor(m => m.LoanOfficer)
  @Html.DropDownListFor(m => m.LoanOfficer, Model.LoanOfficerList, "--Please select--")
  @Html.ValidationMessageFor(m => m.LoanOfficer)
  <input type="submit" value="Create" />
}

相关内容

  • 没有找到相关文章