【问题标题】:JQuery script doesn't get called accurately with the dropdownlist mvc使用下拉列表 mvc 无法准确调用 JQuery 脚本
【发布时间】:2015-08-18 15:07:52
【问题描述】:

这是我第一次在这里发布问题。我是 mvc 的新手。 我想开发两个级联下拉列表。我正在使用 mvc4。这是我所做的。

工厂类

public class Factory
{
    [Key]
    public int FactoryId { get; set; }

    [Required(ErrorMessage = "Required")]
    public string FactoryCode { get; set; }

    [Required(ErrorMessage = "Required")]
    public string FactoryName { get; set; }

    public int City { get; set; }

    public int Country { get; set; }

我有分别具有外键关系的 Country 和 City 类

城市类

public  class City
{

   [Key]
   public int CityId { get; set; }

   [Required(ErrorMessage = "Required")]
   public string CityCode { get; set; }

   [Required(ErrorMessage = "Required")]
   public string CityName { get; set; }

   [ForeignKey("Country")]
   public int CountryId { get; set; }
   public virtual Country Country { get; set; }
}

国家级

public class Country
{
    [Key]
    public int CountryId { get; set; }

    [Required(ErrorMessage = "Required")]
    public string CountryCode { get; set; }

    [Required(ErrorMessage = "Required")]
    public string CountryName { get; set; }

    public virtual List<City> cities { get; set; }
}

工厂控制器

public ActionResult FactoryIndex(string A, int? Id, string sortOrder, string currentFilter, string searchString, int? page)
    {
        var objContext = new KnittingdbContext();

        if (A == "New")
        {
            var model = new Factory();
            ViewData["mdl"] = model;
            ViewBag.CountryList = objContext.Countries;
            ViewBag.Module = A;


        }
.....................

在 IndexView 中渲染局部视图

@if (ViewBag.Module != null)
    {
        if (ViewBag.Module == "New")
        {
            Html.RenderPartial("~/Areas/Masters/Views/Factory/_FactoryCreate.cshtml", ViewData["mdl"]);
        }

_Factory创建局部视图

@Html.DropDownListFor(a=>a.Country,new SelectList(ViewBag.CountryList, "CountryId", "CountryName"), "Select country", new {id="CountryId", @class = "form-control"})

@Html.DropDownListFor(a => a.City; a.City, new SelectList(Enumerable.Empty<SelectListItem>(), "CityId", "CityName"), "Select city", new {@class = "form-control" })

局部视图中的 jquery 脚本

$(function() {

            $('#CountryId').change(function () {
                $.ajax({
                    url: '/Factory/FillCity/',
                    type: "GET",
                    dataType: "JSON",
                    data: { Country: countryId },
                    success: function (cities) {
                        $("#City").html("");
                        $.each(cities, function (i, city) {
                            $("#City").append(
                                $('<option></option>').val(city.CityId).html(city.CityName));
                        });
                    }
                });
            })
        })

FactoryController 中获取相关城市数据的 ActionResult

public ActionResult FillCity(int country)
{
    var db = new KnittingdbContext();
    var cities = db.Cities.Where(c =>c.CountryId == country);
    return Json(cities, JsonRequestBehavior.AllowGet);
}

国家/地区下拉列表有效。 但城市 DDL 不起作用。数据没有被绑定。 当CountryId 被更改时,它涉及到 jquery 脚本。我可以使用警报识别它。但是在脚本中的 URL 属性之后它不起作用。

Success 方法没有被执行。我认为问题在于我呈现网址的方式。我尝试了不同的方法。但还是没能解决。这些视图和控制器位于一个区域中。

请帮助我。提前致谢!

【问题讨论】:

  • 你永远不会向countryId声明或赋值,所以控制器中的country会为空。
  • 首先非常感谢您的回复。正如你所说,我试图为 countryId 分配一个值。我是这样做的。数据{国家:国家}。但它没有用。然后我将其更改为 data{Country:countryId=CountryId}。但仍然不起作用。我认为在从 ddl 选择项目时第一个 ddl 值发生更改后,countryId 被一个值分配,然后将其作为参数发送到控制器方法。请帮忙..
  • 您的代码中还有一些其他问题。您能否发布City 的模型(由db.Cities 返回) - 不妨为您修复它们:)
  • 好吧,正如你所说,我在上面添加了 City 和 Country 类并改进了代码 :)
  • 你在data中的参数Country和你在FillCity中传入的参数不匹配。一个有大写字符。是故意的吗?

标签: jquery json asp.net-mvc-4


【解决方案1】:

您没有将第一个下拉列表的选定值传递给您的控制器方法,因此它会引发异常(country 是 typeof int 并且不能是 null)。你的脚本应该是(注意它不清楚为什么你会通过使用new { id="CountryId" }id 属性从id="Country" 更改为id="CountryId" 所以这个例子使用默认值

var cityDropdown = $("#City"); // cache it to avoid repeatedly searching the DOM
$('#Country').change(function () {
  $.ajax({
    url: '@Url.Action("FillCity", "Factory")', // dont hard code your url's
    type: "GET",
    dataType: "JSON",
    data: { Country: $(this).val() }, // pass the selected value
    success: function (cities) {
        cityDropdown.empty();
        $.each(cities, function (i, city) {
            cityDropdown.append($('<option></option>').val(city.CityId).html(city.CityName));
        });
    }
});

更简单的

$.getJSON('@Url.Action("FillCity", "Factory")', { Country: $(this).val() }, function(cities){
    cityDropdown.empty();
    ... 
});

还请注意,您的方法是序列化 typeof City 的所有属性,包括 CityCodeCountryIdCountry(以及 Country 的所有属性),您从不使用这些属性,所以这是浪费带宽和只会降低性能(并有可能导致循环引用异常)。将您的方法更改为

public JsonResult FillCity(int country)
{
    var db = new KnittingdbContext();
    var cities = db.Cities.Where(c => c.CountryId == country).Select(c => new
    {
      CityId = c.CityId,
      CityName = c.CityName
    };
    return Json(cities, JsonRequestBehavior.AllowGet);
}

请注意,您的代码还存在其他问题,例如,如果您有验证错误并在 POST 方法中返回视图,则不会填充城市下拉列表,从而迫使用户重新选择它。建议您开始使用视图模型并查看此DotNetFiddle中的代码

【讨论】:

  • 谢谢 :) 我会按照你的方式尝试。一旦我完成了,我会告诉你结果。
  • 好的,我已将我的工作解决方案放在下面。我想问题出在脚本上。最后我得到了它的工作。你给了我一些很好的建议。再次感谢:)
  • @ Stephen Muecke,我不得不将脚本更改为 ex 类型:'POST' 而不是 'GET',并且我必须将 FillCity 的参数类型更改为字符串。否则它给了我内部 500 错误。考虑到你的指示,我发现了这些东西。我想用我到目前为止所获得的一点知识来帮助像我这样的新手。这就是我提出这个答案的原因。
  • 您不应该将其更改为 POST(因为您没有更改数据,所以它应该是 GET)。而且您不需要将其更改为string,因为属性CountryIdint 类型,所以很明显您还有很多东西要学习或仍在犯错误。而且您的代码仍然显示您返回一个SelectList,这是毫无意义的额外开销。而且您的脚本有逻辑错误,例如怎么可能输入if (countrySelected == "") - 因为在前一行中,如果countrySelected == "",您将其设置为0
  • 好的,我现在明白了。谢谢你。经过一些研究,我改变了解决方案,因为我无法让它工作。你所有的指示对我都很有价值。我会考虑你的观点再次开发它并让你知道结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 2018-04-12
相关资源
最近更新 更多