为什么我的DropDownListFor中的帖子会出现null异常?

时间:2015-03-10 23:02:50

标签: c# asp.net-mvc

我知道这听起来就像网上的其他问题一样,但事实并非如此。我试图找到正确的答案高低,以免浪费任何人的时间,但无济于事。我还要补充一点,我对MVC.NET很新。

我有一个带有DropDownListFor调用的MVC 4视图,它会在post上抛出null ref异常。我正在尝试测试没有选择任何场景的提交,即选择了默认选择。理想情况下,它会被拾取并用必填字段消息向我大喊大叫。我看到省的模型属性实际上在帖子上设置为-1,因此可行。

现在这是我的问题与其他大多数人不同的地方。我很确定模型正确传递并且填充了SelectList。我在视图中的行上设置了一个断点,并且看到它在爆炸之前填充在帖子上。我的代码看起来像我见过的其他每个例子。

非常感谢您提供的任何帮助。

最后,我将粘贴黄色屏幕信息。

所以这里有一些片段,我删除了大部分片段,这样你就不会被不相关的代码所淹没:

查看:

@using GymManagement.UI.Models
@model UserModel
@Html.DropDownListFor(m => m.Province, Model.ProvinceList, new {@id="ProvincePersonal", @class="inputField", @value="@Model.Province"})

控制器:

public ActionResult CreateMember()
{
    return CreateUser();
}

[HttpPost]
public ActionResult CreateMember(UserModel model)
{
    return CreateUser(model);
}

private ActionResult CreateUser()
{
    var model = new UserModel();

    PrepareModel(model, false);

    return View(model);
}

private ActionResult CreateUser(UserModel model)
{
    if (ModelState.IsValid)
    {
        return DisplayUser(model);
    }

    PrepareModel(model, true);

    return View(model);
}

private void PrepareModel(UserModel model, bool isPostback)
{
    // other items removed for brevity

    if (Session["Provinces"] == null || ((List<Province>)Session["Provinces"]).Count == 0)
    {
        var serviceClient = ServiceProxy.GetLookupService();
        var provinces = serviceClient.GetProvinces(); // Returns List<Province>

        provinces = provinces.OrderBy(p => p.ProvinceName).ToList();
        Session["Provinces"] = provinces;
        model.Provinces = provinces;
    }
    else
    {
        model.Provinces = ((List<Province>)Session["Provinces"]);
    }
}

型号:

// base model
public class BaseModel
{
    public BaseModel()
    {
        Provinces = new List<Province>();
    }
    public List<Province> Provinces { get; set; } 
}

// user model
public int Province { get; set; }

public IEnumerable<SelectListItem> ProvinceList
{
    get
    {
        var list = new SelectList(Provinces, "ProvinceId", "ProvinceName");
        var defaultItem = Enumerable.Repeat(new SelectListItem
        {
            Value = "-1",
            Text = "Select province"
        }, count: 1);

        defaultItem = defaultItem.Concat(list);

        if (Province != 0)
        {
            var selectedItem = Province.ToString();
            var province = defaultItem.First(p => p.Value.Equals(selectedItem));
            province.Selected = true;
        }

        return defaultItem;
    }
}

对象引用未设置为对象的实例。

堆栈追踪:

  

[NullReferenceException:对象引用未设置为对象的实例。]      ASP._Page_Views_user_CreateMember_cshtml.Execute()在c:\ Users \ Mike \ documents \ visual studio 2012 \ Projects \ GymManagement \ GymManagement.UI \ Views \ User \ CreateMember.cshtml:46      System.Web.WebPages.WebPageBase.ExecutePageHierarchy()+279      System.Web.Mvc.WebViewPage.ExecutePageHierarchy()+124      System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,TextWriter writer,WebPageRenderingBase startPage)+180      System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)+379      System.Web.Mvc。&lt;&gt; c__DisplayClass1a.b__17()+32      System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter过滤器,ResultExecutingContext preContext,Func 1 continuation) +613 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList 1过滤器,ActionResult actionResult)+263      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass25.b__22(IAsyncResult asyncResult)+240      System.Web.Mvc。&lt;&gt; c__DisplayClass1d.b__18(IAsyncResult asyncResult)+28      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass4.b__3(IAsyncResult ar)+15      System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)+53      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass4.b__3(IAsyncResult ar)+15      System.Web.Mvc。&lt;&gt; c__DisplayClass8.b__3(IAsyncResult asyncResult)+42      System.Web.Mvc.Async。&lt;&gt; c__DisplayClass4.b__3(IAsyncResult ar)+15      System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+606      System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+288

3 个答案:

答案 0 :(得分:1)

只有您可以逐步调试代码以确定哪个对象为空,从而抛出异常。但真正的问题是你有一个复杂的简单概念,有很多无意义的代码。它可以简单地

查看模型

public Class UserViewModel
{
  ... // other properties of User
  [Display(Name = "Province")]
  [Required(ErrorMessage ="Please select a province")]
  public int ProvinceID { get; set; }
  public SelectList ProvinceList { get; set; }
}

控制器

public ActionResult Create()
{
  UserViewModel model = new UserViewModel();
  ConfigureViewModel(model);
  return View(model);
}

public ActionResult Create(UserViewModel model)
{
  if (!ModelState.IsValid)
  {
    ConfigureViewModel(model);
    return View(model);
  }
  // Save and redirect
}

private void ConfigureViewModel(UserViewModel model)
{
  var provinces = serviceClient.GetProvinces();
  model.ProvinceList = new SelectList(provinces, "ProvinceId", "ProvinceName");
}

查看

@model UserViewModel
@using(Html.BeginForm())
{
  ....
  @Html.LabelFor(m => m.ProvinceID)
  @Html.DropDownListFor(m => m.ProvinceID, Model.ProvinceList, "Please select", new { @class="inputField" })
  @Html.ValidationMessageFor(m => m.ProvinceID)
  ....
  <input type="submit" />
}

答案 1 :(得分:0)

检查每个“ProvinceId”值是否为空,因为您有

var list = new SelectList(Provinces, "ProvinceId", "ProvinceName");

然后

var province = defaultItem.First(p => p.Value.Equals(selectedItem));

答案 2 :(得分:0)

因此,基于斯蒂芬的例子,我把我的观点剥离了,并逐渐添加了元素。事实证明,我的公司地址省与我的个人地址省相冲突。问题是隧道视觉与空引用异常的奇怪位置相结合。感谢大家的想法和帮助!