【问题标题】:MVC null model problemMVC空模型问题
【发布时间】:2010-06-10 15:48:27
【问题描述】:

我创建了两个创建操作。一个调用创建视图,另一个使用 httppost 处理创建视图。

当我调用创建视图时,它会正确发布、下拉列表和所有内容。 问题是当我填写创建表单并单击提交按钮时,我收到错误;

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

我的第一个想法是我将一个空模型传递给 httppost 创建操作.. 如何检查我是否将空模型传递给 httppost 创建操作?

谢谢

【问题讨论】:

    标签: asp.net-mvc model null http-post


    【解决方案1】:

    您究竟是从哪里得到这个异常的?它是在控制器操作中还是在渲染视图时?通常的范例如下:

    public ActionResult New()
    {
        // as you will be creating a new entity you don't need to pass
        // any model here unless your view depends on some property of the model
        return View();
    }
    
    [HttpPost]
    public ActionResult Create(SomeModel model)
    {
        // The model parameter here will be automatically instantiated 
        // by the default model binder and its properties will be 
        // initialized to the values entered by the user in the view
        if (ModelState.IsValid)
        {
            // save the entity
            Repository.Save(model);
            // redirect back to the index action
            return RedirectToAction("Index");
        }
        // validation failed => pass the model to the view in order to
        // preserve values and show validation errors
        return View("New", model);
    }
    

    【讨论】:

    • 似乎我的模型状态无效..我在表单中有大约 5 个字段,但只有 2 个被选中..我还意识到验证消息不会触发..关于这些有什么想法吗?
    猜你喜欢
    • 2011-04-09
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    相关资源
    最近更新 更多