C# 未将对象引用设置为对象(从视图调用 Razor 模型)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18413769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:09:20  来源:igfitidea点击:

Object Reference not set to an object (calling Razor model from View)

c#asp.net-mvcasp.net-mvc-4razor

提问by ArjaaAine

Using C# MVC4

使用 C# MVC4

My View:

我的看法:

@using Universe.Models
@model UserModel
@section css {
<link href="@Url.Content("~/Content/assets/charcreation.css")" rel="stylesheet"/>}
@using (Html.BeginForm("AddUser","Home", FormMethod.Post))
{

<div class="row-fluid">
            <table id="tblBio">
                <tr>
                    <td class="span3">
                        <span class="labeltext">Alias:</span>
                    </td>
                    <td class="span5">
                        @Html.TextBox(Model.Alias)
                    </td>
                    <td class="span4">
                        <span class="ui-state-highlight hidden"></span>
                    </td>
                </tr>

My Model:

我的型号:

public class UserModel
{
    public int Id { get; set; }
    public string Alias { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public bool IsExternal { get; set; }


    public UserModel()
    {

    }

    public UserModel(User user)
    {
        if (user == null) return;
        Alias = user.Alias;
    }
}

But, I keep getting the error:

但是,我不断收到错误消息:

enter image description here

在此处输入图片说明

When I try to debug it, it doesn't even go into the Html.TextBoxmethod or into my model.

当我尝试调试它时,它甚至没有进入Html.TextBox方法或我的模型。

采纳答案by htxryan

Without seeing your controller action, my guess would be that your model is null.

没有看到您的控制器操作,我的猜测是您的模型为空。

In your controller, make sure you are passing an instance of the model to your view. For example:

在您的控制器中,确保您将模型的实例传递给您的视图。例如:

return View(new UserModel());

Instead of:

代替:

return View();

回答by imsurya

You have to pass your Modelin your ControllerAction when return the specific View

返回特定的时,您必须Model在您的ControllerAction 中传递View

return View(new Model());