阿贾克斯查询下拉不填充 [英] Ajax Query Dropdown not populating

查看:189
本文介绍了阿贾克斯查询下拉不填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是很新的MVC和C#,我试图建立一个预约系统,这样,当用户选择一个实践,配镜和日期的JSON查询返回的可用时间。

我的视图模型:

 公共类BookingViewModel
{
    [显示(名称=选择病人)
    公众的Guid PatientId {获得;组; }
    公开的IEnumerable< SelectListItem> PatientList {获得;组; }

    [显示(名称=选择管理规范)]
    公众的Guid PracticeId {获得;组; }
    公开的IEnumerable< SelectListItem> PracticeList {获得;组; }

    [显示(名称=选择配镜师)
    公众的Guid OpticianId {获得;组; }
    公开的IEnumerable< SelectListItem> OpticiansList {获得;组; }

    [显示(NAME =选择日期)
    [数据类型(DataType.Date)
    [DisplayFormat(ApplyFormatInEditMode = TRUE,DataFormatString ={0:DD / MM / YYYY})]
    公开日期时间日期{获得;组; }

    [显示(NAME =选择时间)
    公众的Guid TIMEID {获得;组; }
    公开的IEnumerable< SelectListItem> TimeList {获得;组; }
}
 

控制器:

 公众的ActionResult创建()
    {
        //创建一个新的预订
        BookingViewModel bookingViewModel =新BookingViewModel();
        // Initilises选择列表
        ConfigureCreateViewModel(bookingViewModel);

        返回查看(bookingViewModel);

    }

    // Initilises选择列表
    公共无效ConfigureCreateViewModel(BookingViewModel bookingViewModel)
    {
        //显示配镜名称
        bookingViewModel.OpticiansList = db.Opticians.Select(O =>新建SelectListItem()
        {
            值= o.OpticianId.ToString(),
            文字= o.User.FirstName
        });

        //显示患者姓名
        bookingViewModel.PatientList = db.Patients.Select(P =>新建SelectListItem()
        {
            值= p.PatientId.ToString(),
            文字= p.User.FirstName
        });

        //显示实践名称
        bookingViewModel.PracticeList = db.Practices.Select(P =>新建SelectListItem()
        {
            值= p.PracticeId.ToString(),
            文字= p.PracticeName
        });

        //显示约会时间
        bookingViewModel.TimeList = db.Times.Select(T =>新建SelectListItem()
        {
            值= t.TimeId.ToString(),
            文字= t.AppointmentTime
        });


    }


    //允许管理员创建预订病人
    //邮编:Bookings1 /创建
    [HttpPost]
    [ValidateAntiForgeryToken]
    公众的ActionResult创建(BookingViewModel bookingViewModel)
    {
        //确保日期是在将来
        如果(ModelState.IsValidField(日期)及和放大器; DateTime.Now> bookingViewModel.Date)
        {
            ModelState.AddModelError(日期,在未来的日期请输入);
        }

        //如果模型状态无效
        如果(!ModelState.IsValid)
        {
            // Initilises选择名单
            ConfigureCreateViewModel(bookingViewModel);
            返回查看(bookingViewModel); //返回用户预约页面

        }
        否则//如果模型状态是有效的
        {
            预订预订=新订单();
            //设置isAvail为false
            booking.isAvail = FALSE;
            booking.PracticeId = bookingViewModel.PracticeId;
            booking.OpticianId = bookingViewModel.OpticianId;
            booking.PatientId = bookingViewModel.PatientId;
            booking.Date = bookingViewModel.Date;
            booking.TimeId = bookingViewModel.TimeId;

            //生成新的预订编号
            booking.BookingId = Guid.NewGuid();
            //添加预订到数据库
            db.Bookings.Add(预订);
            //将更改保存到数据库
            db.SaveChanges();
            //重定向用户到订单指数
            返回RedirectToAction(指数);
        }
    }
 

JSON查询返回可用时间:

  // JSON来返回Availiable倍
    [HttpPost]
    公共JsonResult AvailTimes(GUID practiceId中GUID opticianId,日期时间为准)
    {
        变种timesList = db.Bookings.Where(一个=> a.PracticeId == practiceId)
                                   。凡(一个=> a.OpticianId == opticianId)
                                   。凡(A => a.Date ==日)
                                   。凡(A =>!a.isAvail = FALSE)
                                   。选择(A =>新建
        {
            值= a.TimeId,
            文字= a.Time.AppointmentTime
        })了ToList()。

        返回JSON(timesList);
    }
 

Ajax来填充时间:

 <脚本>
$(文件)。就绪(函数(){
    VAR次= $(#TIMEID); //缓存时间元素
    times.prop(已禁用,真正的);
    $(#PracticeId,#OpticianId,#日)。改变(函数(){
        $阿贾克斯({
            网址:@ Url.Action(AvailTimes,预订),
            键入:POST,
            数据:{编号:$(本).VAL()}
        })。完成(功能(timesList){
            执行console.log(timesList)
            times.empty();
            对于(VAR I = 0; I< timesList.length;我++){
                times.append(<期权价值=+ timesList [I] .value的+>中+ timesList [I]。文+< /选项>中);
            }
            times.prop(已禁用,假);
        });
    });
});
< / SCRIPT>
 

查看:

 < D​​IV CLASS =形组>
        @ Html.LabelFor(型号=> model.Date,htmlAttributes:新{@class =控制标签COL-MD-2})
        < D​​IV CLASS =COL-MD-10>
            @ Html.EditorFor(型号=> model.Date,新{htmlAttributes =新{@class =表单控制}})
            @ Html.ValidationMessageFor(型号=> model.Date,,新{@class =文本危险})
        < / DIV>
    < / DIV>
 

在预订时作出IsAvail设置为false,所以我试图做我的JSON LINQ查询是返回可用的齿

然而,当我选择练习,配镜和日期时间仍被禁用。我检查了控制台,我得到以下警告:

  

指定的值'01 / 01/0001,不符合要求的格式,'YYYY-MM-DD。

 <数据-VAL =真正的数据-VAL-日期输入级=形式控制文本框单行=字段选择日期必须是日期。数据-VAL-所需=在选择日期字段是必须的。 ID =日期NAME =日期类型=日期值=01/01/0001/>
 

任何帮助将是很大的AP preciated,谢谢

解决方案

嗯,还有你的code一些问题。

第一:

  

然而,当我选择练习,配镜和日期时间还   禁用。我检查了控制台,我得到以下警告:

如果日期时间输入无效(空),这意味着你发送一个空日期时间值到控制器。由于日期时间不能为空,它采用默认值,这是0001/01/01。

要解决这个问题,你可以使用一个可以为空日期时间参数,像这样的:

  [HttpPost]
公共JsonResult AvailTimes(GUID practiceId中GUID opticianId,日期时间?日)
{
    VAR timesList = db.Bookings
           。凡(一个=> a.PracticeId == practiceId&安培;&安培;
                  a.OpticianId == opticianId和放大器;&安培;)
                  a.isAvail =假放大器;!&安培;);

     如果(date.HasValue)
        timesList = timesList.Where(I => i.Date == date.Value);

    VAR最终= timesList.Select(A =>新建
    {
        值= a.TimeId,
        文字= a.Time.AppointmentTime
    })了ToList()。

    返回JSON(最终);
}
 

二:

在你看来,你在不同的格式EN-US区域性使用日期。

EN-US:MM / DD / YYYY

您的格式(通常是在南美洲使用):DD / MM / YYYY

如果您的服务器使用EN-US区域性,这通常是默认的,它可能无法识别你的日期。

您有几种选择。您可以将您的日期字符串,并使用特定的文化解析。像这样的:

  [HttpPost]
公共JsonResult AvailTimes(GUID practiceId中GUID opticianId,串号)
{
    VAR timesList = db.Bookings
           。凡(一个=> a.PracticeId == practiceId&安培;&安培;
                  a.OpticianId == opticianId和放大器;&安培;)
                  a.isAvail =假放大器;!&安培;);

     如果(!string.IsNullOrWhiteSpace(日期)){
       System.Globalization.CultureInfo yourCulture =
         新System.Globalization.CultureInfo(PT-BR); //例
       日期时间yourDate = DateTime.Parse(日期,yourCulture);
        timesList = timesList.Where(I => i.Date == yourDate);
     }

    VAR最终= timesList.Select(A =>新建
    {
        值= a.TimeId,
        文字= a.Time.AppointmentTime
    })了ToList()。

    返回JSON(最终);
}
 

另一种方式来完成,这是改变整个螺纹/或应用程序的培养。因此,MVC模型绑定会自动识别你的日期格式,并没有解析将是必要的。

有其他技术可用于处理日期格式的Web应用程序。如果您的应用程序只有一个文化访问,你可能不会有任何问题。但是,如果你的应用程序是由多种文化访问,我建议你阅读更多有关在互联网上的日期和时间的技术。

I'm very new to MVC and C# and I am trying to create a booking system so that when a user selects a Practice, Optician and Date a JSON query returns the available times.

My View Model:

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; }      
}

Controller:

    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 Query to return Available times:

    // Json to return Availiable times
    [HttpPost]
    public JsonResult AvailTimes(Guid practiceId, Guid opticianId, DateTime date )
    {
        var timesList = db.Bookings.Where(a => a.PracticeId == practiceId)
                                   .Where(a => a.OpticianId ==opticianId)
                                   .Where(a => a.Date == date)
                                   .Where(a => a.isAvail != false)
                                   .Select(a => new
        {
            Value = a.TimeId,
            Text = a.Time.AppointmentTime
        }).ToList();

        return Json(timesList);
    }

Ajax to populate times:

<script>
$(document).ready(function () {
    var times = $("#TimeId"); // Cache Time element
    times.prop("disabled", true);
    $("#PracticeId","#OpticianId","#Date").change(function () {
        $.ajax({
            url: "@Url.Action("AvailTimes","Bookings")",
            type: "POST",
            data: { Id: $(this).val() }
        }).done(function (timesList) {
            console.log(timesList)
            times.empty();
            for (var i = 0; i < timesList.length; i++) {
                times.append("<option value=" + timesList[i].Value + ">" + timesList[i].Text + "</option>");
            }
            times.prop("disabled", false);
        });
    });
});
</script>

View:

    <div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

When a booking is made the IsAvail is set to false, therefore what I am trying to do with my JSON LINQ Query is return the tines that are available

However when I select a Practice, Optician and Date the Time is still disabled. I checked the console and am getting the following warning:

The specified value '01/01/0001' does not conform to the required format, 'yyyy-MM-dd'.

<input class="form-control text-box single-line" data-val="true" data-val-date="The field Select Date must be a date." data-val-required="The Select Date field is required." id="Date" name="Date" type="date" value="01/01/0001" />

Any help would be greatly appreciated, Thanks

解决方案

Well, there are some problems in your code.

First:

However when I select a Practice, Optician and Date the Time is still disabled. I checked the console and am getting the following warning:

If the DateTime input is disabled (and empty), it means that you are sending a "null" datetime value to the controller. Since datetime cannot be null, it takes the default value, which is '0001/01/01'.

To solve this, you can use a nullable datetime parameter, like this:

[HttpPost]
public JsonResult AvailTimes(Guid practiceId, Guid opticianId, DateTime? date )
{
    var timesList = db.Bookings
           .Where(a => a.PracticeId == practiceId &&
                  a.OpticianId ==opticianId &&)
                  a.isAvail != false &&);

     if (date.HasValue)
        timesList = timesList.Where(i => i.Date == date.Value);

    var final = timesList.Select(a => new
    {
        Value = a.TimeId,
        Text = a.Time.AppointmentTime
    }).ToList();

    return Json(final);
}

Second:

In your view, you are using a date in a different format than en-US culture.

en-US: MM/DD/YYYY

your format (usually used in South America): DD/MM/YYYY

If your server uses the en-US culture, which usually is the default, it might not recognize your date.

You have several choices. You can send your date as string and parse it using a specific culture. Like this:

[HttpPost]
public JsonResult AvailTimes(Guid practiceId, Guid opticianId, string date )
{
    var timesList = db.Bookings
           .Where(a => a.PracticeId == practiceId &&
                  a.OpticianId ==opticianId &&)
                  a.isAvail != false &&);

     if (!string.IsNullOrWhiteSpace(date)) {
       System.Globalization.CultureInfo yourCulture =
         new System.Globalization.CultureInfo("pt-BR"); //example
       DateTime yourDate = DateTime.Parse(date, yourCulture);
        timesList = timesList.Where(i => i.Date == yourDate);
     }

    var final = timesList.Select(a => new
    {
        Value = a.TimeId,
        Text = a.Time.AppointmentTime
    }).ToList();

    return Json(final);
}

Another way to accomplish this is to change the culture of the entire thread/or application. So, the MVC model binder will automatically recognize your date format, and no parse will be necessary.

There are others techniques you can use to handle date format in web application. If your application is accessed by only one culture, you probably won't have any problems. However, if your application is accessed by several cultures, I recommend you to read more about date time techniques on the internet.

这篇关于阿贾克斯查询下拉不填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆