日期:2014-05-17  浏览次数:20480 次

ASP.NET MVC Edit中选中dropdownlist中的对应项
Edit中Province可以对应到model中的对应省份,但是City就不行了,不知道怎么回事,基本一样的代码,不知道问题出哪里,求解。

C# code

    [Table("city")]
    public class city
    {
        [Key]
        [ScaffoldColumn(false)]
        public string cityID { get; set; }
        public string cityname { get; set; }
        public string provinceid { get; set; }
    }


C# code

    [Table("province")]
    public class province
    {
        [Key]
        public string provinceID { get; set; }
        public string provinceName { get; set; }
        public List<city> citys { get; set; }
    }


C# code

    [Table("CompanyInfo")]
    public class CompanyInfo
    {
        [Key]
        public int id { get; set; }
        [Required(AllowEmptyStrings=false, ErrorMessage="请输入单位名称")]
        public string CompanyName { get; set; }

        [Required(AllowEmptyStrings=false, ErrorMessage="请选择省份")]
        public string ProvinceId { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "请选择城市")]
        public string CityId { get; set; }

        public List<AccountInfo> AccountInfos { get; set; }
        public List<DepartmentId> DepartmentIds { get; set; }
    }



C# code

    public class CRMEntities : DbContext
    {
        public DbSet<View_Company_List> View_Company_Lists { get; set; }
        public DbSet<CompanyInfo> CompanyInfos { get; set; }
        public DbSet<AccountInfo> AccountInfos { get; set; }
        public DbSet<DepartmentId> DepartMentIds { get; set; }
        public DbSet<province> provinces { get; set; }
        public DbSet<city> citys { get; set; }
    }



CompanyController.cs中
C# code

 //
        // GET:  /Company/Edit/9
        public ActionResult Edit(int id)
        {
            var companyInfo = CRMDB.CompanyInfos.Find(id);
            ViewBag.ProvinceInf = new SelectList(CRMDB.provinces, "provinceID", "provinceName",companyInfo.ProvinceId);
            ViewBag.CityInf = new SelectList(CRMDB.citys.Where(x => x.provinceid == companyInfo.ProvinceId), "cityID", "cityname", companyInfo.CityId);
            return View(companyInfo);
        }


        //
        // POST: /Company/Edit/
        [HttpPost]
        public ActionResult Edit(CompanyInfo companyInfo)
        {
            if (ModelState.IsValid)
            {
                CRMDB.Entry(companyInfo).State = EntityState.Modified;
                CRMDB.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ProvinceInf = new SelectList(CRMDB.provinces, "provinceID", "provinceName", companyInfo.ProvinceId);
            ViewBag.CityInf = new SelectList(CRMDB.citys.Where(x => x.provinceid == companyInfo.ProvinceId), "cityID", "cityname", companyInfo.CityId);
            return View(companyInfo);
        }



Edit.cshtml中
HTML code

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        &