asp.net mvc:直接在剃刀视图内为模型分配值 [英] asp.net mvc: directly assign value to model inside razor view

查看:58
本文介绍了asp.net mvc:直接在剃刀视图内为模型分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的创建剃刀"视图中包含以下代码段:

I have below snippet inside my Create razor View:

@Html.EditorFor(model => model.UnitPrice)

尝试使用如下语句直接设置UnitPrice:

trying to directly set UnitPrice using statement like this:

@Model.UnitPrice = 100;

我有类似空指针异常的内容:Object reference not set to an instance of an object.

I got something like null pointer exception : Object reference not set to an instance of an object.

在发布以创建发布方法之前,如何为字段分配常量值?

How can I assign constant value to a field before posting to create post method?

推荐答案

在将模型传递给视图之前,需要设置模型中属性的值.假设您的模型是

You need to set the value of the property in the model before you pass the model to the view. Assuming your model is

public class ProductVM
{
    ....
    public decimal UnitPrice { get; set; }
}

然后使用GET方法

ProductVM model = new ProductVM()
{
    UnitPrice = 100M
};
return View(model);

如果该值是适用于所有实例的默认"值,则还可以在无参数的构造函数中设置其值

If the value is a 'default' value that applies to all instances, you can also set its value in a parameter-less constructor

public class ProductVM
{
    public ProductVM()
    {
        UnitPrice = 100M;
    }
    ....
    public decimal UnitPrice { get; set; }
}

请注意,NullReferenceException的原因是您尚未将模型传递给视图.

Note that the reason for the NullReferenceException is that you have not passed a model to your view.

这篇关于asp.net mvc:直接在剃刀视图内为模型分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆