[MVC] obtain view model data in JavaScript code

Source: Internet
Author: User

Anyone who understands MVC knows that the MVC mechanism is to access the action under contoller. The Action organizes the data required by the page and then returns the view (return view ()/return partialview ()) or data (return content ("blah")/return JSON (...)), Sometimes, when a view is returned, data is returned for the page (return view (model )).

 

In fact, there are many forms of value passing between the Controller and view. In addition to the traditional retrun statements that return data to the page, viewdata and viewbag can also be used. Their usage is slightly different in the razor syntax and in the non-razor syntax.

 

For example, if you create an MVC program in the initial home/index action, the following code is available:

 

public ActionResult Index()        {            ViewBag.Message = "Welcome to ASP.NET MVC!";             return View();        }

 


Send a text sentence to the page through viewbag. On the page, we can directly write the same system variable name to access:

 

 


Let's take a look at viewdata. For example, I used viewdata to complete the transfer of the value through viewbag.

Therefore, in the action home/index, the modification code is as follows:

 

 

 public ActionResult Index()        {            //ViewBag.Message = "Welcome to ASP.NET MVC!";            ViewData["Message"] = "Welcome to ASP.NET MVC!!";             return View();        }

 

 

It is in the form of an array. A cursor name is randomly obtained to access data. Here, a text named "message" is defined and saved to viewdata.

On the page, access using the same statement:

 

 

 

If you want to pass multiple variables, simply write another variable and access the variable name on the page to get data.

 

Interestingly, it seems that viewbag and viewdata are different representations of the same thing. For example, we define:

 

public ActionResult Index()        {            ViewBag.Message = "ViewBag.Message";            return View();        }

 


On the page, you can access it either through the viewbag syntax or through the viewdata syntax. Otherwise.

 

 

 

 

But in fact, these are not what I want to talk about in this article. Next I will go to the topic. If I access the data in JavaScript code, I will further explain how to access the data uploaded by the action to the page.

 

In the script code surrounded by <SCRIPT>, you naturally want to use the same syntax for access. We use viewdata for transmission:

 

public ActionResult Index()        {           ViewData["message"] = "Data from server.";            return View();        }

 


Then in the JS Code, it looks like this:

 

<script >        $(function() {            var data =  <%:ViewData["message"] %>;        })    </script>

 


Then an error is reported during the migration,

 

But what's amazing is that we have completed the task. But in fact, it is incorrect to take a closer look, because the statement after the equal sign is not a normal JavaScript statement.

 

To avoid errors and make the code normal, we need to enclose them in quotation marks, so it looks like this:

 

 

var data = ' <%:ViewData["message"] %>';

 

 

This is enough for simple data. However, generally, actions return data of complex types such as models.

 

First, for convenience, create a class file named personalmodel under the model folder. For simplicity, the content is like this:

 

 

public class PersonModel    {        public string Name { get; set; }        public int Age { get; set; }    }

 


A simple object contains only one name attribute of the string type and one age attribute of the integer type.

 

Next, write another method to generate some static data. In actual cases, the data may be retrieved from the database. For convenience of calling this method, I wrote it in the homecontroller class, which looks like this:

 

static List<PersonModel> DummyData()        {            var data = new List<PersonModel>()                           {                               new PersonModel()                                   {                                       Name = "Tom",                                       Age = 20                                   },                               new PersonModel()                                   {                                       Name = "Cat",                                       Age = 5                                   }                           };            return data;        }

 

 


Then we modify the index action to let it return data.

 

public ActionResult Index()        {            var data=DummyData();            return View(data);        }

 


Finally, we will go to the JS Code segment on the page to receive it.

 

<script >        $(function() {            var model = <%= new JavaScriptSerializer().Serialize(Model) %>;            debugger;        })     </script>

 


A debugger is added to facilitate viewing data in the debugging mode in the browser.

Then, go to the browser to check whether the data is obtained (remember that the browser is in debugging mode and press F12 to enter ).

 

 

 

We successfully obtained the transmitted data in the js code snippet and converted the sequence into JSON format.

Then, you can use a statement similar to the following.

 

 

<script >        $(function() {            var model = <%= new JavaScriptSerializer().Serialize(Model) %>;            alert(model[0].Name);            debugger;        })     </script> 

 

 

 

 

The above is only about access in JS. In fact, this is not the main requirement, we just get used to the page usage and don't know what to do when we suddenly need to access the data in JS.

 

How to access the data of this collection type on the page. We all know the situation when a model is transferred to the page.

For example, modify the index action so that it returns only one data record. Of course, the type is personmodle.

 

public ActionResult Index()        {            //var data=DummyData();            var data = new PersonModel()                           {                               Name = "Tom",                               Age = 20                           };            return View(data);        }

 


Note that the previous data (commented out) is of the List <personmodel> type, which is a collection type, but is of the personmodle type. Understanding this is very important for us to obtain data correctly on the page.

 

Then modify the page to a strong type, and then receive the data (as you can see, when we want to obtain data in JS, the page is not required to be a strong type ).

The previous page type looks like this:

 

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

 

 

Now we want to change it to the following:

 

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication17.Models.PersonModel>" %>

 


Then we can use the transmitted data on the page, using a syntax similar to this:

 

 

<p>   Name:<%= Html.DisplayFor(model=>model.Name) %>   Age:<%= Html.DisplayFor(model=>model.Age) %></p>

 

 

When data of the set type is passed, it cannot be accessed in this way. You need to traverse the set and retrieve a single piece of data before using it.

 

Next we will look at the situation of the set type.

Modify the data returned by index action to the original one:

 

 

public ActionResult Index()        {            var data=DummyData();            return View(data);        }

 


Then modify the receiving type of the page to the following:

 

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication17.Models.PersonModel>>" %>

 


Finally, on the page, we need to traverse this set to obtain data. We can use a syntax like this:

 

 

<% foreach(var item in Model) { %>        <p>             Name:<%= Html.DisplayFor(n=>item.Name) %>             Age:<%= Html.DisplayFor(n=>item.Age) %>        </p>    <% } %>

 

 

Here we just briefly talk about the transmission of data from the server to the page in MVC. What is more difficult is to bind the data to the model by sending the data back to the server. Of course, if you use a form and directly submit a submit, all the things are done for you, and the model is easily bound. However, if your page has multiple models, you don't want to use submit but want to write Ajax backhaul. How can we get such data transmission on the server... I will talk about it later.

 

 

 

Articles for reference:

  1. ASP. net mvc using viewdata in JavaScript (stackoverflow)
  2. Using ASP. net mvc V2 editorfor and displayfor with ienumerable <t> generic types
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.