Thursday, May 10, 2018

How to Pass Data from Controller to View in MVC.


How to Pass Data from Controller to View in MVC.

·         ViewData.
·         ViewBag.
·         TempData.

ViewData.

It is a Dictionary object. While retrieving data, the data needs to be Type Cast . ViewData is available only for single Requests. Value gets lost in redirection.
Example 1
1.       Set/Initialize the values you want to pass to view inside the controller action method.

public ActionResult Employee() {
  ViewData["EmpName"] = "Rohit!";
  return View();
 }


2.       Read set value in html.
3.  <html>
4.  <body>
5.   <div>
6.    @ViewData["EmpName"]
7.    </div>
8.   </body>
9.  </html>

Example 2
public ActionResult EmployeeList() {
List<EmployeeModel> empList= new List<EmployeeModel>();
  ViewData["EmpList"] = empList;
  return View();
 }

1.       Read set value in html.
2.  <html>
3.  <body>
4.   <div>
5.    
6.  <ul>
7.  @foreach (var emp in ViewData["EmpList"] as List<EmployeeModel> )
8.  {
9.      <li>
10.        @emp.Name
11.    </li>
12.}
13.</ul>
14.  </div>
15. </body>
16.</html>


No comments:

Post a Comment

Jquery Select and Change selector and event .How to Post data using jquery to mvc and web api action methods

Jquery :Change event in Jquery Method: Demo     $("#drpCountry").change(function () {             var id = $("#DrpCoun...