MVC5中后台提供Json,前台处理Json,绑定给Dropdownlist的例子:
前端:
我们以前在前端定义了两个控件:
<div class="row"> <div class="col-md-1">国家</div> <div class="col-md-11"> @Html.DropDownListFor(model => model.Director.HometownID, MvcEntitiyFrameWork.ViewModels.HometownViewModel.GetHometownSelectList(), htmlAttributes: new { @class = "form-control", @style = "width:120px;" }) </div> </div> <div class="row" style="margin-bottom:2px"> <div class="col-md-1">导演</div> <div class="col-md-11"> @Html.DropDownListFor(model => model.DirectorID, MvcEntitiyFrameWork.ViewModels.DirectorViewModel.GetDirectorSelectList(Model.Director.HometownID.ToString()), htmlAttributes: new { @class = "form-control", @style = "width:120px;" }) @Html.ValidationMessageFor(model => model.DirectorID, "", new { @class = "text-danger" }) </div> </div>
然后我们在脚本中执行如下代码:
特别的一点,我们在上面代码中貌似没指定控件的ID,但是运行以后在页面是可以看到控件的ID的,从而,我从运行后的界面得到ID来使用。
<script type="text/javascript"> $("#Director_HometownID").change( function () { GetDirector($(this).val()); } ); function GetDirector(message) { var option = { url: ‘/Movies/GetDirectorList‘, type: ‘get‘, chche: false, dataType: ‘json‘, data: { _htid: message }, //发送服务器数据 success: function (data) { //成功事件 $("#DirectorID").empty(); $.each(data, function (i, item) { $("<option></option>").val(data[i].Value).text(data[i].Text).appendTo($("#DirectorID")); }); }, error: function (XMLHttpRequest, textStatus, errorThrown) { //发送失败事件 alert(textStatus ); } }; //进行异步传输 $.ajax(option); } </script>
我们的后台,controller中定义如下,返回ActionResult
public ActionResult GetDirectorList(string _htid) { try { //方法一 Ok //var selectList = db.Directors.Where(a => a.HometownID.ToString() == _htid).Select(a => new SelectListItem //{ // Text = a.DirectorName, // Value = a.DirectorID.ToString() //}); //return Json(selectList, JsonRequestBehavior.AllowGet); //方法二 也Ok List<Director> list = db.Database.SqlQuery<Director>("select DirectorID,DirectorName,HometownID from Directors where HometownID=‘" + _htid + "‘").ToList(); SelectList pList = new SelectList(list, "DirectorID", "DirectorName"); return Json(pList, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return null; } }
前端就可以得到返回值,对dropdownlistbox数据进行绑定了(这里是dropdownlistbox级联筛选数据的应用)
时间: 2024-10-31 20:11:48