Returning ASP.net View with data variables

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

      

and my opinion:

<%= a; %>

      

I am getting the error:

'a' is not declared. It may be unavailable due to its security level.

+3


source to share


1 answer


You are very close to the solution! just add the model to access its properties below:

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

      



But I would suggest that avoiding anonymous type in your controller is return View(new{a=foo,b=bar})

not a good idea. Follow the instructions below.

  • Create model

    namespace ModelCentral{
    public class AbModel
    {
      public int a{get;set;};
      public int b{get;set;};
    }
    }
    
          

  • then edit your controller action like this

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

  • finally in your opinion

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

+1


source







All Articles