GVKun编程网logo

结合使用Ajax和dropdownlist mvc3(使用ajax的步骤)

17

本篇文章给大家谈谈结合使用Ajax和dropdownlistmvc3,以及使用ajax的步骤的知识点,同时本文还将给你拓展Ajax联动动态为@Html.DropDownListFor赋值、ASP.NE

本篇文章给大家谈谈结合使用Ajax和dropdownlist mvc3,以及使用ajax的步骤的知识点,同时本文还将给你拓展Ajax联动动态为@Html.DropDownListFor赋值、ASP.NET MVC 3中的DropDownList、ASP.NET MVC DropDownListFor 列表值在 AJAX POST 请求后未更新、Asp.net MVC5中Html.DropDownList的使用等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

结合使用Ajax和dropdownlist mvc3(使用ajax的步骤)

结合使用Ajax和dropdownlist mvc3(使用ajax的步骤)

选择下拉列表选项时,有什么方法可以刷新页面的某些部分(例如div / span)?请注意,我使用的是razor语法。

如果是,那么请提供一些示例代码。

答案1

小编典典

是的,您可以订阅onchange活动。

@Html.DropDownListFor(m => m.ItemId, Model.ItemList, "Select an item...", new { onchange = "somefunction();" })

可能是这样(真实示例):

   @using (Ajax.BeginForm("Action", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "divtoupdate", InsertionMode = InsertionMode.Replace }))    {        @Html.DropDownListFor(m => m.ItemId, Model.ItemList, "Select an item...", new { onchange = "doSubmit($(this).parents(''form''));" })    }

然后具有此javascript函数(或类似功能)

<script>function doSubmit(form){  // event.preventDefault(); doesn''t work in IE8 so do the following instead  (event.preventDefault) ? event.preventDefault() : event.returnValue = false;  form.submit();}</script>

编辑:此示例假设您使用的是非侵入式验证(因此使用jQuery),并且想要提交表单,但是显然您可以为onchange事件调用任何javascript函数,然后执行所需的任何操作…

Ajax联动动态为@Html.DropDownListFor赋值

Ajax联动动态为@Html.DropDownListFor赋值

<script type="text/javascript">
 function getTeams(deptCode) {
 $.ajax({
 url: "@Url.Action("GetTeams","User")",data: { departmentCode: deptCode },dataType: "json",type: "POST",error: function () {
 alert("An error occurred.");
 },success: function (data) {
 var items = "";
 $.each(data,function (i,item) {
 items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
 });

 $("#@Html.IdFor(m => m.TeamId)").html(items);
 }
 });
 }

 $(document).ready(function () {
 $("#@Html.IdFor(m => m.DepartmentCode)").change(function () {
 var deptCode = $("#@Html.IdFor(m => m.DepartmentCode)").val();

 getTeams(deptCode);
 });
 });
 </script>


根据部门ID(deptCode)获取该部门下的组(Team)。

Controller:

User的GetTeams(string departmentCode)返回一个集合,通过

$.each(data,item) 
进行循环添加。

ASP.NET MVC 3中的DropDownList

ASP.NET MVC 3中的DropDownList

<div>
    @Html.LabelFor(model => model.Category)
</div>
<div>

    @Html.EditorFor(model => model.Category)
    @Html.ValidationMessageFor(model => model.Category)
</div>

这给了我一个标签和一个文本框.如何获取带有静态选择项的下拉列表来代替文本框.请帮忙.我是ASP.NET MVC的新手.我需要Razor语法的解决方案/建议.

解决方法

@Html.DropDownListFor( model => model.Category,new SelectList(new [] {"cat1","cat2","cat3"}) );

ASP.NET MVC DropDownListFor 列表值在 AJAX POST 请求后未更新

ASP.NET MVC DropDownListFor 列表值在 AJAX POST 请求后未更新

如何解决ASP.NET MVC DropDownListFor 列表值在 AJAX POST 请求后未更新?

在我看来,我有一个 JQuery DatePicker 和一个 DropDownListFor,其中包含一个列表,其中填充了来自我的模型的 HH:MM 格式的数据类型字符串的时间。现在,当我从 DatePicker 中选择一个日期时,我将使用 AJAX POST 调用将它从我的视图发送到我的控制器。在我的 Controller 中,我终于通过调试发现我的模型确实从我的视图中收到了正确的值,并且我的模型中的列表与时间也进行了调整。

但是,在我看来,带有小时列表的 DropDownListFor 没有调整。我已经尝试了各种方法,例如将 ModelState.Clear() 添加到我的 ActionMethod 等等,但都没有成功。你能帮我解决这个问题吗? 非常感谢!

查看 (HTML)

@using (Html.BeginForm("Create","Appointment",FormMethod.Post,new { @}))
        {
            @Html.ValidationSummary(true,"",new { @})
            <divhttps://www.jb51.cc/tag/ott/" target="_blank">ottom">
                <div>
                    <label>Voornaam*</label>
                    @Html.TextBoxFor(m => m.AppointmentModel.CustomerName,new { @,id = "customername",type = "text",placeholder = "Uw voornaam" })
                    @Html.ValidationMessageFor(model => model.AppointmentModel.CustomerName,new { @})
                </div>
                <div>
                    <label>Achternaam*</label>
                    @Html.TextBoxFor(m => m.AppointmentModel.CustomerLastName,id = "customerlastname",placeholder = "Uw achternaam" })
                    @Html.ValidationMessageFor(model => model.AppointmentModel.CustomerLastName,new { @})
                </div>
            </div>
            <divhttps://www.jb51.cc/tag/ott/" target="_blank">ottom p-4">
                <label>E-mail*</label>
                @Html.TextBoxFor(m => m.AppointmentModel.Email,id = "email",placeholder = "Uw e-mailadres" })
                @Html.ValidationMessageFor(model => model.AppointmentModel.Email,new { @})
            </div>
            <divhttps://www.jb51.cc/tag/ott/" target="_blank">ottom p-4">
                <label>Mobiele nummer*</label>
                @Html.TextBoxFor(m => m.AppointmentModel.MobileNumber,id = "mobilenumber",placeholder = "Uw mobiele nr." })
                @Html.ValidationMessageFor(model => model.AppointmentModel.MobileNumber,new { @})
            </div>
            <divhttps://www.jb51.cc/tag/ott/" target="_blank">ottom p-4 position-relative">
                <label>Datum afspraak*</label>
                <div>
                    @Html.EditorFor(m => m.AppointmentModel.AppointmentDate,new
               {
                   htmlAttributes = new { @,@,id = "appointmentdate" }
               })
                    @Html.ValidationMessageFor(model => model.AppointmentModel.AppointmentDate,new { @})
                </div>
            </div>
            <divhttps://www.jb51.cc/tag/ott/" target="_blank">ottom p-4 position-relative">
                <label>Tijdstip afspraak*</label>
                <div>
                    @Html.DropDownListFor(m => m.ChosenAppointmentTime,new SelectList(Model.DateTimeModel.Times,"Value","Text"),@,@id = "appointmenttime" })
                </div>  ---> THIS IS THE DROPDOWNLISTFOR I AM TALKING ABOUT
            </div>
            <divhttps://www.jb51.cc/tag/ott/" target="_blank">ottom p-4">
                <label>Bericht</label>
                @Html.TextAreaFor(m => m.AppointmentModel.Message,id = "message",@,placeholder = "Typ hier uw bericht",col = "1",row = "1" })
            </div>
            <div>
                <div>
                    <button type="submit"id="submit-button" data-toggle="modal" data-target="#exampleModal"><i></i> Maak afspraak</button>
                    <buttonid="resultLoading" type="submit" disabled>
                        <spanrole="status" aria-hidden="true"></span>
                        Loading...
                    </button>
                </div>
            </div>
        }

查看(JQuery)

$(''#appointmentdate'').change(function () { /* WHEN I SELECT A NEW DATE FROM THE DATEPICKER,I GET THE SELECTED VALUE AND I SEND IT TO THE VIEW */
        var selectedDate = $("#appointmentdate").val();

        $.ajax({
            url: "/Appointment/SetSelectedDate",data: { date: selectedDate },type: "POST",dataType: "text",success: function (data) {
                console.log(data);
            },error: function (passparams) {
                console.log(passparams);
            }
        });
        //location.reload();
    });

控制器


//PROPERTIES
        private static List<string> listofAppointmentDates { get; set; }
        private static string SelectedDate { get; set; }
        private viewmodel VM { get; set; } = new viewmodel();
        private string DateOfToday { get; set; } = DateTime.Now.ToString("yyyy/MM/dd");

        public async Task<ActionResult> Index()
        {
            using (var dbContext = new ProjectContext())
            {
                await Task.Run(() => listofAppointmentDates = AppointmentBAL.GetAppointments().Select(x => x.AppointmentDate).ToList()); 
--> GET ALL THE RECORDS FROM DB AND ONLY SELECT THE DATES PROPERTY FROM THE MODEL (APPOINTMENTDATE = yyyy/mm/dd - HH:MM FORMAT)
            }

            if (SelectedDate == null)
            {
                VM.DateTimeModel.FindTimesAndRemove(listofAppointmentDates,DateOfToday);
                SelectedDate = DateOfToday;
            }
            else if (SelectedDate == DateOfToday)
            {
                VM.DateTimeModel.FindTimesAndRemove(listofAppointmentDates,DateOfToday);
            }
            else if (SelectedDate != null && SelectedDate != DateOfToday)
            {
                VM.DateTimeModel.FindTimesAndRemove(listofAppointmentDates,SelectedDate);
            }
            return View(VM);
        }

        public ActionResult SetSelectedDate(string date) --> Selected date in DatePicker from View
        {
            string formattedDate = date.Replace("-","/"); --> Format incoming date from View

            if (SelectedDate != formattedDate)
            {
                VM.DateTimeModel.ResetTimeList();
                VM.DateTimeModel.FindTimesAndRemove(listofAppointmentDates,formattedDate);
                SelectedDate = date;
            }
            else
            {
                VM.DateTimeModel.FindTimesAndRemove(listofAppointmentDates,formattedDate);
            }
            _ = VM;  --> HERE I dubBLE CHECKED THE viewmodeL OBJECT THAT CONTAINS THE DATETIMEMODEL THAT HOLDS THE LIST OF AVAILABLE TIMESLOTS. IT SHOWS ME THE LIST WITH THE VALUES THAT SHUD BE IN THERE

            ModelState.Clear();
            return View("Index");
        }

视图模型

    public class viewmodel
    {
        public AppointmentModel AppointmentModel { get; set; } = new AppointmentModel();
        public DateTimeModel DateTimeModel { get; set; } = new DateTimeModel(); --> HOLDS THE LIST OF TIMES
        public string ChosenAppointmentTime { get; set; }
    }

日期时间模型

public class DateTimeModel
    {

        private static List<System.Web.Mvc.SelectListItem> times = new List<System.Web.Mvc.SelectListItem>
        {
            new System.Web.Mvc.SelectListItem() { Value =  "11:00",Text = "11:00",disabled = false },new System.Web.Mvc.SelectListItem() { Value =  "11:30",Text = "11:30",new System.Web.Mvc.SelectListItem() { Value =  "12:00",Text = "12:00",new System.Web.Mvc.SelectListItem() { Value =  "12:30",Text = "12:30",new System.Web.Mvc.SelectListItem() { Value =  "13:00",Text = "13:00",new System.Web.Mvc.SelectListItem() { Value =  "13:30",Text = "13:30",new System.Web.Mvc.SelectListItem() { Value =  "14:00",Text = "14:00",new System.Web.Mvc.SelectListItem() { Value =  "14:30",Text = "14:30",new System.Web.Mvc.SelectListItem() { Value =  "15:00",Text = "15:00",new System.Web.Mvc.SelectListItem() { Value =  "15:30",Text = "15:30",new System.Web.Mvc.SelectListItem() { Value =  "16:00",Text = "16:00",new System.Web.Mvc.SelectListItem() { Value =  "16:30",Text = "16:30",new System.Web.Mvc.SelectListItem() { Value =  "17:00",Text = "17:00",new System.Web.Mvc.SelectListItem() { Value =  "17:30",Text = "17:30",new System.Web.Mvc.SelectListItem() { Value =  "18:00",Text = "18:00",disabled = false }
        };
        public IEnumerable<System.Web.Mvc.SelectListItem> Times
        {
            get
            {
                return times;
            }
        }
        public void FindTimesAndRemove(List<string> listtocheck,string datetoInspect) ---> Here I am checking the list with all the dates that came from the DB and the second parameter is the active date value from the DatePicker in the View.
        {
            var listofSelectedDateWithTime = listtocheck.Where(x => x.Contains(datetoInspect)).ToList();

            for (int i = 0; i < listofSelectedDateWithTime.Count; i++)
            {
                times.RemoveAll(x => x.Text == listofSelectedDateWithTime[i].Substring(13,5)); ---> removing the timeslots from the static list that are already taken.
            }
        }
        public void ResetTimeList() ---> Here I am filling the list up again.
        {
            times = new List<System.Web.Mvc.SelectListItem>
            {
                new System.Web.Mvc.SelectListItem() { Value =  "11:00",disabled = false }
            };
        }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Asp.net MVC5中Html.DropDownList的使用

Asp.net MVC5中Html.DropDownList的使用

一.静态下拉列表项的绑定

在下拉列表中绑定静态项,我们可以通过 SelectListItem 的集合作为数据源的下拉列表。
1     @Html.DropDownList("dropRoles", new List<SelectListItem>()
2     {
3         new SelectListItem() { Text= "Yes", Value = "true" },
4         new SelectListItem() { Text= "No", Value = "false", Selected = true }
5     }, "Select ..."),new { @,})

 在上面的代码片段中,

第一个参数是下拉列表中的名称;

第二个参数是 SelectListItem 要用作数据源的下拉列表中的集合和第三个参数是默认值,如果将选中"选择 = true"不在任何的 SelectListItem 中指定。

第三个参数是在下拉列表中显示的默认默认空项。

第四个参数是写入下拉列表中的样式/类或其他 HTML 属性( htmlObjectAttributes)。

二、绑定多个表数据

 @Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList)

 控制器操作方法代码

1
2
3
4
5
6
7
8
9
10
11
var  data =  from  in  db.PersonalDetails
                        join  in  db.Files
                        on  p.AutoId  equals  f.PersonalDetailsId
                        select  new
                        {
                            PersonName = p.FirstName,
                            MyFileName = f.FileName
                        };
 
             SelectList list =  new  SelectList(data,  "MyFileName" "PersonName" );
             ViewBag.Roles = list;

 

在上面的代码片段中,我们加入了两个表使用 LINQ,形成具有到 PersonName 和 MyFileName 属性的对象。转换成通过指定dataTextFileld dataValueField 的下拉列表。
 此时集合然后被设置为 ViewBag.Roles,用作数据源的下拉列表中的视图。
 

三、在下拉列表中绑定模型

在下拉列表中绑定一个模型属性,使用下面的代码片段。
public IEnumerable<SelectListItem> Categories { get; set; }
在该控制器的操作方法中设置此属性值,
model.Categories = db.CategoryModels.Where(c => c.SectionId == sectionId &&
 c.Active == true).OrderBy(ct => ct.CategoryName).ToList().
Select(x => new SelectListItem { Value = x.CategoryId.ToString(), Text = x.CategoryName }).ToList();
在上面的代码片段中,注意第三行的代码中,是从列表中选择的所有项目,创建SelectListItem 对象所指定的值为类别 id 和类别名称作为文本。
 
当此集合有界的下拉列表中时,类别 id 作为项的值和类别名称用作下拉列表项的文本。
四、更改下拉列表项的回发

 在 ASP.NET MVC 中的窗体中更改下拉列表项自动回发,我们可以在 htmlObjectAttributes 中这样指定 onchange 属性。

@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList, "Select ...", 
new { @,, onchange = "this.form.submit();" })
在上面的代码片段,onchange 属性会迫使该窗体以提交它在服务器上,当用户更改下拉列表中的选定内容。

我们今天的关于结合使用Ajax和dropdownlist mvc3使用ajax的步骤的分享已经告一段落,感谢您的关注,如果您想了解更多关于Ajax联动动态为@Html.DropDownListFor赋值、ASP.NET MVC 3中的DropDownList、ASP.NET MVC DropDownListFor 列表值在 AJAX POST 请求后未更新、Asp.net MVC5中Html.DropDownList的使用的相关信息,请在本站查询。

本文标签: