c# - ASP.net 返回带有数据变量的 View

标签 c# sql asp.net-mvc

public ActionResult Index()
{
   return View("test", new {a = 1, b = 2});
}

我的观点:

<%= a; %>

我得到一个错误:

'a' is not declared. It may be inaccessible due to its protection level.

最佳答案

您离解决方案很近了!只需添加模型即可访问其属性,如下所示

  //in your view      
  <%= Model.a %>

但我想建议避免在 Controller 中使用匿名类型 return View(new{a=foo,b=bar}) 不是一个好主意。 请按照以下步骤操作

  • 创建模型

    namespace ModelCentral{
    public class AbModel
    {
      public int a{get;set;};
      public int b{get;set;};
    }
    }
    
  • 然后像这样编辑你的 Controller Action

    public ActionResult Index()
    {
     var model = new AbModel() {a = 1, b = 2};
       return View("test",model);
    }
    
  • 终于在你的视野中

     <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ModelCentral.AbModel>" %>
    
     <%= Model.a%>
    

关于c# - ASP.net 返回带有数据变量的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31068077/

相关文章:

c# - 预定义类型 'System.Object' 未定义或导入 .net 4.6

c# - 在 WCF 客户端/服务器应用程序中计算 UTC/本地日期时间转换的最佳方法

c# - 在Dispose()中处理异常

c# - Max in linq to NHibernate 对于数据库中不存在的数据

asp.net - 列出未使用的 ID

php - 如何使用php日期函数从oracle日期字段中选择日期和时间

php - 检查 MySQL 中的日期范围

c# - 如何从 Request.Form 获取所有元素值而不用 .GetValues ("ElementIdName"准确指定哪个元素值)

asp.net-mvc - Kendo 数据源过滤器未按预期工作

C# - 从序列中获取种子