ASP.NET C#MVC将值从Controller传递给cshtml

时间:2018-03-21 20:05:54

标签: 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();
     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> 

...我的问题是,如何显示值?在此先感谢您的任何帮助。

3 个答案:

答案 0 :(得分:2)

您需要使用razor syntax

使用您的示例:

@{
    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> 

答案 1 :(得分:1)

您需要将值发送到返回

中的视图
return View(objCustomer);

这将允许模型绑定器启动,使用ActionResult对象中的值填充@model类型的值。

如果您使用的是razor而不是<%=语法,那么您也应该使用@ razor语法替换它们,如Matt Griffiths' answer所示。

答案 2 :(得分:-1)

完整解决您的问题:

控制器操作:您需要从控制器操作

发送对象以进行查看
 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>