c# – 在表单发布时将下拉列表中的选定值从视图传递到控制器

我有这些模型和视图模型.当表单发布以创建条目时,在控制器POST方法中,WardID和DoctorID的选定值变为零.

查看代码

@model NewClient.HospitalMgt.ViewModel.PatientAdmissionViewModel
.... 
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <div class="editor-label">
            @Html.LabelFor(model => model.Admission.WardID, "Ward")
        </div>
        <div class="editor-field">
            @Html.DropDownList("WardID", String.Empty)
            @Html.ValidationMessageFor(model => model.Admission.WardID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Admission.DoctorID, "Doctor")
        </div>
        <div class="editor-field">
            @Html.DropDownList("DoctorID", String.Empty)
            @Html.ValidationMessageFor(model => model.Admission.DoctorID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Patient.PatientName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Patient.PatientName)
            @Html.ValidationMessageFor(model => model.Patient.PatientName)
        </div>
        .... //more controls for properties of Patient

        <div class="editor-label">
            @Html.LabelFor(model => model.Admission.AdmissionNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Admission.AdmissionNumber)
            @Html.ValidationMessageFor(model => model.Admission.AdmissionNumber)
        </div>
        .... //more controls for properties of Admission
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

控制器代码

public ActionResult Create()
{
    ViewBag.WardID = new SelectList(db.Wards, "WardID", "WardNumber");
    ViewBag.DoctorID = new SelectList(db.Doctors, "DoctorID", "DoctorName");
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PatientAdmissionViewModel Id)
{
    if (ModelState.IsValid)
    {
        var c = new Patient()
        {
            Address = Id.Patient.Address,
            ContactNumber = Id.Patient.ContactNumber,
            EmergencyContact = Id.Patient.EmergencyContact,
            PatientName = Id.Patient.PatientName,
        };
        var a = new Admission()
        {
            AdmissionNumber = Id.Admission.AdmissionNumber,
            AdmissionDate = Id.Admission.AdmissionDate,
            **WardID = Id.Admission.WardID, //becomes zero 
            DoctorID = Id.Admission.DoctorID //becomes zero** 
        };
        db.Patients.Add(c);
        db.Admissions.Add(a);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.WardID = new SelectList(db.Wards, "WardID", "WardNumber", Id.Admission.WardID);
    ViewBag.DoctorID = new SelectList(db.Doctors, "DoctorID", "DoctorName", Id.Admission.DoctorID);
    return View(Id);
}

模型和视图模型

//[NotMapped]
public class PatientAdmissionViewModel 
{
    public Patient Patient { get; set; }
    public Admission Admission { get; set; }
}

public class Patient
{
    public int PatientID { get; set; }
    [Required(ErrorMessage = "A Patient Name is required")]
    public string PatientName { get; set; }
    public string Address { get; set; }
    [Required(ErrorMessage = "A Contact Number is required")]
    public string ContactNumber { get; set; }
    public string EmergencyContact { get; set; }
    public virtual Ward Ward { get; set; }
}

public class Admission
{
    public int AdmissionID { get; set; }
    public string AdmissionNumber { get; set; }
    public Nullable<int> PatientID { get; set; }
    public int WardID { get; set; }
    public int DoctorID { get; set; }
    public System.DateTime AdmissionDate { get; set; }
    public virtual Ward Ward { get; set; }
    public virtual ICollection<PatientPayment> PatientPayments { get; set; }
}

最佳答案 您使用@ Html.DropDownList(“WardID”,String.Empty)和@ Html.DropDownList(“DoctorID”,String.Empty)分别生成名称=“WardID”和name =“DoctorID”的输入,但是您建模不包含具有这些名称的属性(但它包含名为Admission的属性,其中包含这些属性).

“视图模型”实际上不是视图模型(视图模型不应包含编辑时作为数据模型的属性).您的视图模型还应包含SelectList的属性,以便您可以强烈绑定到模型.您的视图模型需要

public class PatientAdmissionViewModel
{
    [Display(Name = "Ward"]
    [Required(ErrorMessage = "Please select a ward")]
    public int? SelectedWard { get; set; }
    [Display(Name = "Doctor"]
    [Required(ErrorMessage = "Please select a doctor")]
    public IEnumerable<SelectListItem> WardList { get; set; }
    public int? SelectedDoctor { get; set; }
    public IEnumerable<SelectListItem> DoctorList { get; set; }

    public string PatientName { get; set; }
    ... // other properties of Patient that you need in the view

    public string AdmissionNumber{ get; set; }
    ... // other properties of Admission that you need in the view
}

并在GET方法中,初始化视图模型的实例,设置其属性并将其返回到视图

public ActionResult Create()
{
    var model = new PatientAdmissionViewModel()
    {
        WardList = new SelectList(db.Wards, "WardID", "WardNumber"),
        DoctorList = new SelectList(db.Doctors, "DoctorID")
    };
    return View(model);
}

并在视图中

@Html.DropDownListFor(m => m.SelectedWard, Model.WardList, "-Please select-")
....
@Html.DropDownListFor(m => m.SelectedDoctor, Model.DoctorList, "-Please select-")

最后,在POST方法中,初始化数据模型的新实例,根据视图模型中的值设置其属性并保存数据模型.

我还建议你阅读What is ViewModel in MVC?的答案.

点赞