在mvc中的ajax jquery中将更改下拉列表更改为复选框 [英] change dropdown list to checkbox in ajax jquery in mvc

查看:157
本文介绍了在mvc中的ajax jquery中将更改下拉列表更改为复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我使用jquery ajax使用级联下拉列表,它可以工作,但是我需要将第二个下拉列表更改为复选框,以根据从第一个下拉列表中选择的区域以及项目选择使用复选框需要保存在数据库中。但我是MVC的新人,Iam无法以正确的方式给出复选框的代码。



控制器

  public ActionResult Create()
{
ViewBag.DistrictId = new SelectList(db.DistrictMasters,Id,DistrictName);

return View();
}

public JsonResult GetPosts(string id)
{
列表< SelectListItem> posts = new List< SelectListItem>();
var postList = this.Getpost(Convert.ToInt32(id));
var postData = postList.Select(m => new SelectListItem()
{
Text = m.PostName,
Value = m.Id.ToString(),
});
return Json(postData,JsonRequestBehavior.AllowGet);
}

public IList< PostMaster> Getpost(int DistrictId)
{
return db.PostMasters.Where(m => m.DistrictID == DistrictId).ToList();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async任务< ActionResult>创建([Bind(Include =Id,PostId,DistrictId)]代理代理,FormCollection formdata)
{
if(ModelState.IsValid)
{
db.Agents。添加(剂);
等待db.SaveChangesAsync();
return RedirectToAction(Index);
}

return View(agent);
}

查看创建

  @model A.Models.Agent 

@using(Html.BeginForm())
{
@ Html.AntiForgeryToken()
< div class =form-horizo​​ntal>
@ Html.ValidationSummary(true,,new {@class =text-danger})
< div class =form-group>
@ Html.LabelFor(model => model.PostMaster.DistrictID,DistrictName,htmlAttributes:new {@class =control-label col-md-2})
< div class = COL-MD-10 >
@ Html.DropDownList(DistrictId,ViewBag.DistrictId as SelectList, - 请选择 - ,新{style =width:250px})
< / div>
< / div>

< div class =form-group>
@ Html.LabelFor(model => model.PostId,PostName,htmlAttributes:new {@class =control-label col-md-2})
< div class = COL-MD-10\" >
@ Html.DropDownList(PostMaster,新的SelectList(string.Empty,Value,Text), - 请选择 - ,新的{style =width:250px,@class =dropdown1})
< / div>
< / div>
< div class =form-group>
< div class =col-md-offset-2 col-md-10>
< input type =submitvalue =Createclass =btn btn-default/>
< / div>
< / div>
< / div>
}

< script type =text / javascript>
$(document).ready(function(){
// District Dropdown Selectedchange event
$(#DistrictId)。change(function(){
$( #PostMaster)。empty();
$ .ajax({
type:'POST',
url:'@ Url.Action(GetPosts)',//调用json方法
dataType:'json',
data:{id:$(#DistrictId)。val()},
//获取所选的帖子ID
success: function(posts){
$ .each(posts,function(i,post){
$(#PostMaster)。append('< option value ='+ post.Value +
post.Text +'< / option>');
});
},
错误:function(ex){
alert('无法检索帖子'+ ex);
}
});
return false;
})
});



我认为这部分是我需要改变jquery,但是我不能这样做。

  success:function(posts){
$ .each(post,function(i,post){
$(#PostMaster)。append('< option value ='+ post.Value +'>'+
post .Text +'< / option>');
});
},


< div class =form-group>
@ Html.LabelFor(model => model.PostId,PostName,htmlAttributes:new {@class =control-label col-md-2})
< div class = COL-MD-10\" >
@ Html.DropDownList(PostMaster,新的SelectList(string.Empty,Value,Text), - 请选择 - ,新的{style =width:250px,@class =dropdown1})

< / div>
< / div>

这是我的代码部分。任何人都可以帮助我找到解决方案

解决方案

与往常一样,首先创建视图模型来表示你想要的视图

  public class AgentVM 
{
....
[必需(ErrorMessage =请选择一个区域)]
[Display(Name =District)]
public int? SelectedDistrict {get;组; }
public IEnumerable< SelectListItem> DistrictList {get;组; }
public IEnumerable< CityVM>城市{get;组; }
}
public class CityVM
{
public int ID {get;组; }
public string Name {get;组; }
public bool IsSelected {get;组; }
}

并创建一个 EditorTemplate for CityVM 。在 /Views/Shared/EditorTemplates/CityVM.cshtml

  @model CityVM 
< div>
@ Html.HiddenFor(m => m.ID)
@ Html.HiddenFor(m => m.Name)
< label>
@ Html.CheckBoxFor(m => m.IsSelected)
< span> @ Model.Name< / span>
< / label>
< / div>

,并在ajax调用中返回部分视图 - _FetchCities.cshtml

  @model AgentVM 
@ Html.EditorFor(m => m.Cities )

在主视图中

  @model AgentVM 
@using(Html.BeginForm())
{
....
@ Html.LabelFor(m => ; m.SelectedDistrict)
@ Html.DropDownListFor(m => m.SelectedDistrict,Model.DistrictList,请选择)
@ Html.ValidationMessageFor(m => m.SelectedDistrict)
....
< div id =cites>
@ Html.EditorFor(m => m.Cities)
< / div>
< input type =submitvalue =Create/>
}

然后您的控制器代码将被

  public ActionResult Create()
{
AgentVM model = new AgentVM();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Create(AgentVM model)
{
if(!ModelState.IsValid)
{
ConfigureViewModel模型);
return View(model);
}
//获取所选城市的ID
IEnumerable< int> selectedCities = model.Cities.Where(x => x.IsSelected).Select(x => x.ID);
//初始化数据模型
//从视图模型中映射其值
//保存并重定向
}
public PartialViewResult FetchCities(int id)
{
//根据需要调整属性名称
IEnumerable< CityVM> cities = db.Cities.Where(x => x.DistrictID == id).Select(x => new CityVM
{
ID = x.CityID,
Name = x .CityName
});
AgentVM model = new AgentVM()
{
城市=城市
};
return PartialView(_ FetchCities,model);

}
private ConfigureViewModel(AgentVM model)
{
model.DistrictList = new SelectList(db.DistrictMasters,Id,DistrictName);
//以下仅适用于您编辑现有值的视图
if(model.Cities == null&& model.SelectedDistrict.HasValue)
{
//根据SelectedDistrict获取城市,并映射到CityVM的集合
}
}

最后你的脚本将是

  var url ='@ Url.Action(FetchCities)' ; 
var cities = $('#cities');
$('#SelectedDistrict')。change(function(){
var selectedCity = $(this).val();
if(!selectedCity){
cities。 empty();
return;
}
$ .get(url,{id:selectedCity},function(data){
cities.html(data);
}
})


In my project I used cascaded drop down list using jquery ajax and it works, but I need to change the second drop down list to checkbox to select the City based on the districts selected from the first drop down list and also the items selected using checkbox need to be saved in the database. But I am new to MVC and Iam not able to give the code for check box in the correct way.

controller

public ActionResult Create()
    {
        ViewBag.DistrictId = new SelectList(db.DistrictMasters, "Id", "DistrictName");

        return View();
    }

 public JsonResult GetPosts(string id)
    {
        List<SelectListItem> posts = new List<SelectListItem>();
        var postList = this.Getpost(Convert.ToInt32(id));
        var postData = postList.Select(m => new SelectListItem()
        {
            Text = m.PostName,
            Value = m.Id.ToString(),
        });
        return Json(postData, JsonRequestBehavior.AllowGet);
    }

public IList<PostMaster> Getpost(int DistrictId)
    {
        return db.PostMasters.Where(m => m.DistrictID == DistrictId).ToList();
    }

  [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "Id,PostId,DistrictId")] Agent agent, FormCollection formdata)
    {
        if (ModelState.IsValid)
        {
            db.Agents.Add(agent);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(agent);
    }

view create

@model A.Models.Agent

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
 <div class="form-horizontal">
  @Html.ValidationSummary(true, "", new { @class = "text-danger" })
 <div class="form-group">
        @Html.LabelFor(model => model.PostMaster.DistrictID, "DistrictName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("DistrictId", ViewBag.DistrictId as SelectList, "-- Please Select  --", new { style = "width:250px" }) 
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PostId, "PostName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("PostMaster", new SelectList(string.Empty, "Value", "Text"), "-- Please select --", new { style = "width:250px", @class = "dropdown1" })
        </div>
    </div>
 <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<script type="text/javascript">
$(document).ready(function () {
    //District Dropdown Selectedchange event
    $("#DistrictId").change(function () {
        $("#PostMaster").empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetPosts")', // Calling json method
            dataType: 'json',
            data: { id: $("#DistrictId").val() },
            // Get Selected post id.
            success: function (posts) {
                $.each(posts, function (i, post) {
                    $("#PostMaster").append('<option value="' + post.Value + '">' +
                         post.Text + '</option>');
                });
            },
            error: function (ex) {
                alert('Failed to retrieve post.' + ex);
            }
        });
        return false;
    })
});

I think this part which I need to change in jquery, but I am not able to do it

 success: function (posts) {
                $.each(posts, function (i, post) {
                    $("#PostMaster").append('<option value="' + post.Value + '">' +
                         post.Text + '</option>');
                });
            },


  <div class="form-group">
        @Html.LabelFor(model => model.PostId, "PostName", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("PostMaster", new SelectList(string.Empty, "Value", "Text"), "-- Please select --", new { style = "width:250px", @class = "dropdown1" })       

        </div>
    </div>

this is my part of my code. can anyone please help me to find the solution

解决方案

As always, start by creating view models to represent what your want in the view

public class AgentVM
{
    ....
    [Required(ErrorMessage = "Please select a District")]
    [Display(Name = "District")]
    public int? SelectedDistrict { get; set; }
    public IEnumerable<SelectListItem> DistrictList { get; set; }
    public IEnumerable<CityVM> Cities { get; set; }
}
public class CityVM
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

And create an EditorTemplate for CityVM. In /Views/Shared/EditorTemplates/CityVM.cshtml

@model CityVM
<div>
    @Html.HiddenFor(m => m.ID)
    @Html.HiddenFor(m => m.Name)
    <label>
        @Html.CheckBoxFor(m => m.IsSelected)
        <span>@Model.Name</span>
    </label>
</div>

and a partial view to be returned in your ajax call - _FetchCities.cshtml

@model AgentVM
@Html.EditorFor(m => m.Cities)

And in the main view

@model AgentVM
@using (Html.BeginForm())
{
    ....
    @Html.LabelFor(m => m.SelectedDistrict)
    @Html.DropDownListFor(m => m.SelectedDistrict, Model.DistrictList, "Please select")
    @Html.ValidationMessageFor(m => m.SelectedDistrict)
    ....
    <div id="cites">
        @Html.EditorFor(m =>m.Cities)
    </div>
    <input type="submit" value="Create" />
}

Your controller code will then be

public ActionResult Create()
{
    AgentVM model = new AgentVM();
    ConfigureViewModel(model);
    return View(model);
}
[HttpPost]
public ActionResult Create(AgentVM model)
{
    if (!ModelState.IsValid)
    {
        ConfigureViewModel(model);
        return View(model);
    }
    // Get the ID's of the selected cities
    IEnumerable<int> selectedCities = model.Cities.Where(x => x.IsSelected).Select(x => x.ID);
    // Initialize you data model
    // Map its values from the view model
    // Save and redirect
}
public PartialViewResult FetchCities(int id)
{
    // Adjust property names as required
    IEnumerable<CityVM> cities = db.Cities.Where(x => x.DistrictID == id).Select(x => new CityVM
    {
        ID = x.CityID,
        Name = x.CityName
    });
    AgentVM model = new AgentVM()
    {
        Cities = cities
    };
    return PartialView("_FetchCities", model);

}
private ConfigureViewModel(AgentVM model)
{
    model.DistrictList = new SelectList(db.DistrictMasters, "Id", "DistrictName");
    // The following would only be applicable to a view where you editing existing values
    if (model.Cities == null && model.SelectedDistrict.HasValue)
    {
        // Get cities based on SelectedDistrict and map to a collection of `CityVM`
    }
}

And finally your script will be

var url = '@Url.Action("FetchCities")';
var cities = $('#cities');
$('#SelectedDistrict').change(function() {
    var selectedCity = $(this).val();
    if (!selectedCity) {
        cities.empty();
        return;
    }
    $.get(url, { id: selectedCity }, function(data) {
        cities.html(data);
    }
})

这篇关于在mvc中的ajax jquery中将更改下拉列表更改为复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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