Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在ASP.NET MVC中使用viewmodel显示计算字段?_C#_Asp.net Mvc_Viewmodel - Fatal编程技术网

C# 如何在ASP.NET MVC中使用viewmodel显示计算字段?

C# 如何在ASP.NET MVC中使用viewmodel显示计算字段?,c#,asp.net-mvc,viewmodel,C#,Asp.net Mvc,Viewmodel,我想在视图中显示一个计算字段,因此我尝试创建如下视图模型: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Facturacion.Models { public class Test { public int testId

我想在视图中显示一个计算字段,因此我尝试创建如下视图模型:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;    

namespace Facturacion.Models
{
    public class Test
    {
        public int testId { get; set; }    

        [Required]
        public decimal price { get; set; }
    }    

    public class TestViewModel
    {
        [Key]
        public int testId { get; set; }
        public Test test { get; set; }
        public decimal price { get; set; }
        public decimal calculated { get; set; }    

        public TestViewModel(Test test)
        {
            Test = test;
            calculated = Test.price * 2;
        }
    }
}
它给了我一个错误,所以我更改了构造函数:

        public TestViewModel(Test test)
        {
            var foo = test;
            calculated = foo.price * 2;
        }
但是现在当我构建项目时,它创建了一个名为“TestViewModels”的表,因此我无法访问Tests表中的数据

我认为viewmodel不应该有id,但如果没有id,架子工将不会生成控制器


使用viewmodel在视图中显示计算字段的正确方法是什么?

我可以在不使用viewmodel的情况下解决它

namespace Facturacion.Models
{
    public class Test
    {
        public int testId { get; set; }    

        [Required]
        public decimal price { get; set; }

        public decimal calculated
        {
            get
            {
                return (decimal)(price*2);
            }
        }
    }
}

请注意,计算字段没有set方法。

视图模型不应包含
测试
,并且所有视图模型都需要无参数构造函数,否则它们将不会在回发时绑定。您的视图模型也应该位于单独的文件夹中(例如“ViewModels”)。在您的控制器方法中,您获取数据模型,初始化视图模型的新实例,并将数据模型属性映射到它,然后将视图模型返回到视图。并且“它给了我一个错误”-什么错误?错误表示模型。Test是一种类型,但它的使用方式类似于变量,这是因为行
Test=Test
Test
(大写字母T)是一种类型-模型中的属性是
Test
(小写)删除
[Key]
属性您的模型是业务层的一部分,因此像这里这样添加属性是正确的方法,因为计算是业务逻辑,而不是UI。