簡體   English   中英

級聯下拉菜單-無效值

[英]Cascading Drop Down - Invalid Value

我是MVC的新手,很難從數據庫創建級聯下拉列表。 選擇實踐后,將在該實踐中工作的配鏡師進行填充,但不會將其保存到dataView模型中:

public class BookingViewModel
{
    [Display (Name = "Select Patient")]
    public Guid PatientId { get; set; }
    public IEnumerable<SelectListItem> PatientList { get; set; }

    [Display(Name = "Select Practice")]
    public Guid PracticeId { get; set; }
    public IEnumerable<SelectListItem> PracticeList { get; set; }

    [Display(Name = "Select Optician")]
    public Guid OpticianId { get; set; }
    public IEnumerable<SelectListItem> OpticiansList { get; set; }

    [Display(Name = "Select Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Date { get; set; }

    [Display(Name = "Select Time")]
    public Guid TimeId { get; set; }
    public IEnumerable<SelectListItem> TimeList { get; set; }  
}

}

我的預訂控制器:

  public ActionResult Create()
    {
        // Creates a new booking
        BookingViewModel bookingViewModel = new BookingViewModel();
        // Initilises Select List
        ConfigureCreateViewModel(bookingViewModel);

        return View(bookingViewModel);

    }

    // Initilises Select List 
    public void ConfigureCreateViewModel(BookingViewModel bookingViewModel)
    {
        // Displays Opticians Name 
        bookingViewModel.OpticiansList = db.Opticians.Select(o => new SelectListItem()
        {
            Value = o.OpticianId.ToString(),
            Text = o.User.FirstName
        });

        // Displays Patients name 
        bookingViewModel.PatientList = db.Patients.Select(p => new SelectListItem()
        {
            Value = p.PatientId.ToString(),
            Text = p.User.FirstName
        });

        // Displays Practice Name
        bookingViewModel.PracticeList = db.Practices.Select(p => new SelectListItem()
        {
            Value = p.PracticeId.ToString(),
            Text = p.PracticeName
        });

        // Displays Appointment Times 
        bookingViewModel.TimeList = db.Times.Select(t => new SelectListItem()
        {
            Value = t.TimeId.ToString(),
            Text = t.AppointmentTime
        });


    }


    // Allows Admin to create booking for patient 
    // POST: Bookings1/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(BookingViewModel bookingViewModel)
    {
        // to ensure date is in the future
        if (ModelState.IsValidField("Date") && DateTime.Now > bookingViewModel.Date)
        {
            ModelState.AddModelError("Date", "Please enter a date in the future");
        }



        // if model state is not valid
        if (!ModelState.IsValid)
        {
            // Initilises Select lists
            ConfigureCreateViewModel(bookingViewModel);
            return View(bookingViewModel); // returns user to booking page


        }
        else // if model state is Valid
        {
            Booking booking = new Booking();
            // Sets isAvail to false
            booking.isAvail = false;
            booking.PracticeId = bookingViewModel.PracticeId;
            booking.OpticianId = bookingViewModel.OpticianId;
            booking.PatientId = bookingViewModel.PatientId;
            booking.Date = bookingViewModel.Date;
            booking.TimeId = bookingViewModel.TimeId;

            // Generates a new booking Id
            booking.BookingId = Guid.NewGuid();
            // Adds booking to database
            db.Bookings.Add(booking);
            // Saves changes to Database
            db.SaveChanges();
            // Redirects User to Booking Index
            return RedirectToAction("Index");
        }
    }

 // Json for cascading drop down, to allow the user to select an optician from the selected practice.
    [HttpPost]
    public JsonResult Opticians(Guid Id)
    {
        var opticianList = db.Opticians.Where(a => a.PracticeId == Id).Select(a => a.User.FirstName).ToList();

        return Json(opticianList);
    }

我的觀點:

<script>
$(document).ready(function () {
    $("#OpticianId").prop("disabled", true);
    $("#PracticeId").change(function () {
        $.ajax({
            url : "@Url.Action("Opticians","Bookings")",
            type : "POST",
            data : {Id : $(this).val() }
        }).done(function (opticianList) {
            $("#OpticianId").empty();
            for (var i = 0; i < opticianList.length; i++) {
                $("#OpticianId").append("<option>" + opticianList[i] + "</option>");
            }
            $("#OpticianId").prop("disabled", false);
        });
    });
});

 <div class="form-group">
        @Html.Label("Select Optician :", new { @class = "col-md-2 control-label" })
        <div class="col-md-10">

            @Html.DropDownListFor(model => model.OpticianId, Model.OpticiansList, "-Please Select-", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.OpticianId, "", new { @class = "text-danger" })
        </div>
    </div>

級聯下拉列表可以正常工作,但是當我嘗試將其保存到數據庫時,我收到了驗證錯誤-

值“名稱”對於選擇配鏡師無效

任何幫助將不勝感激。 謝謝

因為您的Opticians(Guid Id)方法僅從Opticians表中返回User.FirstName屬性,所以OpticianId的下拉列表的選定值回發了選定的FirstName值,該值無法綁定到Guid屬性。 您生成的html是

<option>Some Name</option>

但這必須是

<option value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">Some Name</option>

更改方法以返回ID和Name屬性

[HttpPost]
public JsonResult Opticians(Guid Id)
{
    var opticianList = db.Opticians.Where(a => a.PracticeId == Id).Select(a => new
    {
      Value = a.OpticianId,
      Text = a.User.FirstName
    }).ToList();
    return Json(opticianList);
}

然后將腳本更改為

var opticians = $("#OpticianId"); // cache elements you repeatedly refer to
opticians.prop("disabled", true);
$("#PracticeId").change(function () {
    $.ajax({
        url : "@Url.Action("Opticians","Bookings")",
        type : "POST",
        data : {Id : $(this).val() }
    }).done(function (opticianList) {
        opticians.empty();
        $.each(opticianList, function(index, item) {
            opticians.append($('<option></option>').val(item.Value).text(item.Text));
        });
        opticians.prop("disabled", false);
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM