简体   繁体   中英

ASP.net return View with data variables

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

and my view:

<%= a; %>

I get an error:

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

You are quite near the solution! just add model to access its property as bellow

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

But I would like to advice to avoid anonymous type in your controller return View(new{a=foo,b=bar}) is not a good idea. Please follow these steps

  • Create a model

     namespace ModelCentral{ public class AbModel { public int a{get;set;}; public int b{get;set;}; } } 
  • then edit your controller action as this

     public ActionResult Index() { var model = new AbModel() {a = 1, b = 2}; return View("test",model); } 
  • finally in your view

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM