Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.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
ASP.NET C#MVC将值从控制器传递到cshtml_C#_Asp.net_Asp.net Mvc_Razor - Fatal编程技术网

ASP.NET C#MVC将值从控制器传递到cshtml

ASP.NET C#MVC将值从控制器传递到cshtml,c#,asp.net,asp.net-mvc,razor,C#,Asp.net,Asp.net Mvc,Razor,我不熟悉使用Razor页面,因此在模型目录中有一个类,其值如下: public int Id { set; get; } public string CustomerCode { set; get; } public double Amount { set; get; } 在控制器(.cs文件)中,我有以下内容: public ActionResult Index() { Customer objCustomer = new Customer(); objCustome

我不熟悉使用Razor页面,因此在模型目录中有一个类,其值如下:

public int Id { set; get; }
public string CustomerCode { set; get; }
public double Amount { set; get; }
在控制器(.cs文件)中,我有以下内容:

 public ActionResult Index()
 {
     Customer objCustomer = new Customer();
     objCustomer.Id = 1001;
     objCustomer.CustomerCode = "C001";
     objCustomer.Amount = 900.78;
     return View();
 }
…现在,我想通过Index.cshtml页面显示值,但当我运行应用程序时,我只会得到我键入的与值相反的实际代码:

…以下是.cshtml页面的设置方式:

@model Mvccustomer.Models.Customer

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div>
    The customer id is : <%= Model.Id %> <br />
    The customer id is : <%= Model.CustomerCode %> <br />
    The customer id is : <%= Model.Amount %> <br />
</div> 
@model Mvccustomer.Models.Customer
@{
ViewBag.Title=“Index”;
}
指数
客户id为:
客户id为:
客户id为:

…我的问题是,如何获得要显示的值?提前感谢您的帮助

您需要将值发送到返回中的视图

return View(objCustomer);
这将允许模型绑定器启动,用ActionResult对象中的值填充
@model
类型的值

如果您使用razor而不是
,则需要使用

以您的例子:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div>
    The customer id is : @Model.Id <br />
    The customer id is : @Model.CustomerCode <br />
    The customer id is : @Model.Amount <br />
</div> 
@{
ViewBag.Title=“Index”;
}
指数
客户id为:@Model.id
客户id为:@Model.CustomerCode
客户id为:@Model.Amount

问题的完整解决方案:

控制器操作:您需要从控制器操作将对象发送到视图

 public ActionResult Index()
     {
         Customer objCustomer = new Customer();
         objCustomer.Id = 1001;
         objCustomer.CustomerCode = "C001";
         objCustomer.Amount = 900.78;
         return View(objCustomer);
     }
视图:您需要使用@for Razor语法

 @model Mvccustomer.Models.Customer

    @{
        ViewBag.Title = "Index";
    }

    <h2>Index</h2>
    <div>
        The customer id is : @Model.Id <br />
        The customer id is : @Model.CustomerCode <br />
        The customer id is : @Model.Amount <br />
    </div> 
@model Mvccustomer.Models.Customer
@{
ViewBag.Title=“Index”;
}
指数
客户id为:@Model.id
客户id为:@Model.CustomerCode
客户id为:@Model.Amount

不知道为什么我的答案被否决了?请更新投票否决我答案的原因