DropDownListFor()和500个错误

时间:2014-02-28 17:19:16

标签: c# asp.net-mvc-3

当我通过点击提交按钮发布我的AJAX表单时出现500错误。处理AJAX帖子的控制器正在获取数据,但是当我返回部分视图时,通过这一行,我得到了500:

return PartialView("_SiteSurveyNewClubTeam", model);

我返回部分返回而不是HTTP状态代码的原因是因为如果我不这样做,我的一个动态下拉列表将返回未填充状态。也许我在这里把自己钉在角落里。

违规的DropDownListFor()中提供的数据类型我认为是正确的并且顺序正确:(string, IList<SelectListItem>)

错误

The ViewData item that has the key 'DistrictSelected' is of type 'System.String' 
but must be of type 'IEnumerable<SelectListItem>'.

查看模型声明

public IList<SelectListItem> DistrictSelect { get; set; }
public string DistrictSelected { get; set; }

错误来源是我视图中的这一行

<span class="formColumn2">@Html.DropDownListFor(model => model.DistrictSelected, Model.DistrictSelect)</span>

不确定我为什么会这样做。有什么想法吗?

由于

以下是处理AJAX表单

的代码
[HttpPost]
public ActionResult ProcessFormANewClubTeam(FormANewClubTeamViewModel model)
{
    var httpStatus = HttpStatusCode.BadRequest;
    var cosponsors = new List<NewClubSponsor>();
    var errorMessages = new StringBuilder();
    var tasks = new NewClubBuilderTasks();
    var clubKeyNumber = tasks.GetClubKeyNumber();
    var masterCustomerId = tasks.GetMasterCustomerId();
    bool exceptionRaised = false;

    if (ModelState.IsValid)
    {


        if (model.NewClub_Id > 0)
        {
                //Load the entity to be partially-updated
                NewClub newClub = db.NewClubs.Single(nc => nc.Id == model.NewClub_Id);

                //Set the values for the fields to be updated
                newClub.District = model.DistrictSelected;
                newClub.Division = model.DivisionSelected;
                newClub.Region = Utility.Personify.GetRegionFromDistrict(newClub.District);
                newClub.ClubCounselorMasterCustomerId = model.ClubCounselorMasterCustomerId;
                newClub.ClubCounselorContact = model.ClubCounselorContact;
                newClub.ClubCounselorEmail = model.ClubCounselorEmail;
                newClub.ClubCounselorPhone = model.ClubCounselorPhone;
                newClub.DateUpdated = DateTime.Now;

                try
                {
                    //Execute the UPDATE
                    var dbResult = db.SaveChanges() > 0;
                    httpStatus = HttpStatusCode.OK;

                }
                catch (SqlException ex)
                {
                    //Catch exceptions here
                }

           // return new HttpStatusCodeResult((int) httpStatus);
           return PartialView("_SiteSurveyNewClubTeam", model);

    } else {

            var errors = ModelState
            .Where(x => x.Value.Errors.Count > 0)
            .Select(x => new {x.Key, x.Value.Errors})
            .ToArray();

            return new HttpStatusCodeResult((int) httpStatus);

    }
}

1 个答案:

答案 0 :(得分:1)

您必须在帖子操作中的区域选择列表中重新填充选择列表项。您发布的viewmodel将DistrictSelect设置为null,这就是渲染部分时获得该异常的原因。