使用AJAX MVC 4

时间:2015-05-06 18:16:11

标签: c# jquery ajax asp.net-mvc

我有一个包含2个@DownDownListFor'助手的视图:

    @using (Html.BeginForm("CreateOneWayTrip", "Trips"))
    {
        @Html.ValidationSummary(false);
        <fieldset>
            <legend>Enter Your Trip Details</legend>

            <label>Start Point</label>
            @Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces, new { @Id = "province_dll", @class = "form-control" })
            @Html.DropDownListFor(m => m.StartPointCity, (SelectList)ViewBag.Cities, new { @Id = "city_dll", @class = "form-control" })

            <p style="float: none; text-align: center;">
                <button type="submit" value="Create" class="btn btn-info btn-circle btn-lg">
                    <i class="fa fa-check"></i>
                </button>

                <button type="submit" value="Create" class="btn btn-warning btn-circle btn-lg">
                    <i class="fa fa-times"></i>
                </button>
            </p>
        </fieldset>
    }

这是我用来捕获数据的临时模型:

 public class CaptureCreateTrip
 {
    [Required]
    [Display(Name = "Trip ID")]
    public string TripID { get; set; }

    [Required]
    public string StartPointProvince { get; set; }

    [Required]
    public string StartPointCity { get; set; }
}

在创建页面时填充其中一个DropsDownList,并根据用户在第一个DropDownList中选择的选项填充第二个。为实现这一目标,我使用的是ajax。我使用的javascript看起来像这样:

&#13;
&#13;
$("#province_dll").change(function () {
        $.ajax({
            url: 'getCities/Trips',
            type: 'post',
            data: {
                provinceId: $("#province_dll").val()
            }
        }).done(function (response) {
            $("cities_dll").html(response);
        });
    });
&#13;
&#13;
&#13;

以下是AJAX调用的控制器:

  [HttpPost]
  public ActionResult getCicites(int provinceId)
  {
      var lstCities = new SelectList(new[] { "City1", "City2", "City3" });

      return Content(String.Join("", lstCities));
  }

到目前为止一切正常 - 当我在省DropDown中选择一个值时,javascript事件会触发,而Controller操作会将选择列表值返回到Cities DropDown,但问题是数据(格式为Action返回的数据不正确。我通过创建一个Paragraph元素并使用ajax调用的返回值更新它的文本来测试它,它是:&#34; System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc。选择列表项&#34;

*注意:我是ajax的新手,在学习Jquery和AJAX的过程中。

3 个答案:

答案 0 :(得分:31)

您收到字符串var lstCities = new SelectList(new[] { "City1", "City2", "City3" });的原因是:IEnumerable<SelectListItem>返回String.Join("", lstCities).ToString()调用每个SelectListItem方法"System.Web.Mvc.SelectListItemSystem"返回Text的集合中的项目(不是SelectListItem的{​​{1}}属性的值)

填充第二个下拉列表的最佳方法是返回包含城市集合的json,并在ajax成功回调中更新DOM。没有理由创建SelectList - 它只是不必要的额外开销,并且您必须将至少3倍的数据返回给客户端(客户端没有C#SelectListItem类的概念

public JsonResult FetchCities(int provinceId) // its a GET, not a POST
{
    // In reality you will do a database query based on the value of provinceId, but based on the code you have shown
    var cities = new List<string>() { "City1", "City2", "City3" });
    return Json(cities, JsonRequestBehavior.AllowGet);
}

然后在脚本中(不确定为什么您已将默认idid="StartPointProvince"修改为id="province_dll",但是)

var url = '@Url.Action("FetchCities", "Trips")'; // Don't hard code your url's!
var cities = $('#city_dll'); // cache it
$("#province_dll").change(function () {
    var id = $(this).val(); // Use $(this) so you don't traverse the DOM again
    $.getJSON(url, { provinceId: id }, function(response) {
        cities.empty(); // remove any existing options
        $.each(response, function(index, item) {
            cities.append($('<option></option>').text(item));
        });
    });
});

修改

除了OP的评论之外,如果数据库包含带有字段CitiesID的表名Name,那么控制器方法将类似于

public JsonResult FetchCities(int provinceId) // its a GET, not a POST
{
    var cities = db.Cities.Select(c => new
    {
      ID = c.ID,
      Text = c.Text
    }
    return Json(cities, JsonRequestBehavior.AllowGet);
}

并且创建选项的脚本将是

$.each(response, function(index, item) { // item is now an object containing properties ID and Text
    cities.append($('<option></option>').text(item.Text).val(item.ID));
});

答案 1 :(得分:5)

您可以尝试以下方法吗?

这是我几天前发帖的帖子。 字体:Dynamic DropDownLists In MVC 4 Form

您应该在省ddl的change事件中创建一个ajax调用。 此呼叫将请求某个操作并返回所选省份的城市。

$("province_dll").change(function(){
    $.ajax({
         url: 'getCitiesController/getCitiesAction',
         type: 'post',
         data: {
               provinceId: provinceIdVar
         }
    }).done(function(response){
         $("cities_dll").html(response);
    }); 
});

在行动中:

[HttpPost]
public ActionResult getCicitesAction(int provinceId)
{
     var cities = db.cities.Where(a => a.provinceId == provinceId).Select(a => "<option value='" + a.cityId + "'>" + a.cityName + "'</option>'";

     return Content(String.Join("", cities));
}

答案 2 :(得分:2)

让它变得更简单

  • 第1步:服务器端功能/数据

    function FetchP()
    {
        var url = '@Url.Action("FetchP", "Your_Controller")'; 
        var PDD= $("#PDD");
        var ODD= $("#ODD").val(); 
    
        $.getJSON(url, { O: ODD}, function (response) {
            PDD.empty(); 
            debugger;
            $.each(response, function (index, item) {
                debugger;
                var p = new Option(item.Text, item.Value);
                PDD.append(p);
            });
        });
    }
    
  • 第2步:客户端功能/数据解释器

    @Html.DropDownList("ODD", ViewBag.OList as IEnumerable<SelectListItem>, new { @id = "ODD", @class = "form-control", @onchange= "FetchP()" })
    
  • 第3步:致电 - 客户端功能/开始

  • 列表1:

    @Html.DropDownList("PDD", ViewBag.PList as IEnumerable<SelectListItem>,new { @id = "PDD", @class = "form-control"})
    
  • 清单2:

    C:\users\%USERNAME%\documents\workspace