ASP.Net MVC – How to pass data between view and controller

Reference: http://www.cnblogs.com/hangwei/p/4466856.html

In this article we will discuss the way to pass data between view and controller. There will be three parts:

  • From Controller to View
  • From View to Controller
  • Between Actions

In ASP.NET WebForms,  we use the following methods to pass data between view and controller

  • Query String (URL)
  • Session
  • Cookie
  • Application
  • Server.Transfer

Here we will talk about the ways in MVC.

From Controller to View

1. ViewBag

Usage:

In Controller:

ViewBag.Test123 = "Hello World.";

In View:

@ViewBag.Test123

ViewBag is a dynamical type here.

2. ViewData

Usage:

In Controller:

ViewData["Test123"] = "Hello World. This is ViewData";

In View:

@ViewData["Test123"]

ViewData is a dictionary. It inherits from IDictionary<string,object> interface.

3. TempData

Usage:

In Controller:

TempData["tmpData"] = "I am TempData...";

In View:

@TempData["tmpData"]

TempData is also a dictionary. It inherits from IDictionary<string,object> interface and it is one-off.

4. Model

Usage:

In Controller:

public ActionResult Index()
{
    return View("UserInfo", GetTestData());//GetTestData()
}

In View:

@model IEnumerable<MVC5Demo.Models.UserInfoViewModel>

and in the body element:

<tbody>
    @foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(p => item.UserName)</td>
        <td>@(item.Sex == 0 ? "Female" : "Male")</td>
        <td>@Html.DisplayFor(p => item.Age)</td>
        <td>@Html.DisplayFor(p => item.Dept)</td>
        <td>@Html.ActionLink("Edit", "Edit", "UserInfo", new { id=item.UserID.ToString() },null)
        @Html.ActionLink("Delete", "Delete", "UserInfo", new { id = item.UserID.ToString() }, new { onclick="return confirm('Are you sure to delete"+item.UserName+"?');" })
        </td>
    </tr>
    }
</tbody>

It’s the most common used way in ASP.NET MVC.

From View to Controller

In View:

1. Use Html.BeginForm to submit the form

@using(Html.BeginForm("actionName","controllerName"))
{
    <div>Contents</div>
    <div>...</div>
    <input type="submit" value="Submit" />
}

2. Use Html.BeginRouteForm to submit the form

@Html.BeginRouteForm("RouteName", new { controller = "userinfo",
action="save", userID = Model.UserID, userName = Model.UserName },
FormMethod.Post)
{
    <div>Contents</div>
    <div>...</div>
    <input type="submit" value="Submit" />
}

3. Use traditional HTML Form

<form id="postForm" action="@Url.Action("Save")" method="post">
    <div>Contents</div>
    <div>...</div>
    <input type="submit" value="Submit" />
</form>

4. Use Ajax.BeginForm to submit the form asynchronously

@Ajax.BeginForm("actionName", new AjaxOptions { Url="",OnSuccess="",HttpMethod="get" })
{
    <div>Contents</div>
    <div>...</div>
    <input type="submit" value="Submit" />
}

Controller:

1. Parameters passing

The controller receives each individual parameters from the view.

[HttpPost]
public ActionResult Save(string username, int sex, int age, string dept)

2. Model passing

[HttpPost]
public ActionResult Save(UserInfoViewModel item)

Here the model is what we bind using @model in the view.

3. Form collection passing

[HttpPost]
public ActionResult Save(FormCollection fc)

Here we need to bind the form data to object manually.

UserInfoViewModel userInfo = new UserInfoViewModel();
TryUpdateModel<UserInfoViewModel>(userInfo, fc);

4. Traditional way

Using HttpContext, we can still use the following object: Application ,  Server,  Session,  Request,  Response and Cache.

Between Actions

1. Use RedirectToAction

You can pass object:

public ActionResult Index()
{
    return RedirectToAction("Index", "Home", new UserInfoViewModel { 
        UserID = Guid.NewGuid(), 
        UserName = "zhangsan", 
        Sex = 1, 
        Age = 20, 
        Dept = "hr" 
    });
}

and received by:

public class HomeController : Controller
{
    public ActionResult Index(UserInfoViewModel model)
    {
        //consume model
        //...
    }
}

Or you can pass individual parameters:

public ActionResult Index()
{
    return RedirectToAction("Index", "Home", new { 
        UserID = Guid.NewGuid(), 
        UserName = "zhangsan"
    });
}

and receive by:

public class HomeController : Controller
{
    public ActionResult Index(string userID, string userName)
    {
        //consume userID, userName
        //...
    }
}

2. Use TempData

Set the value in one action:

TempData["userName"] = "zhangsan";

And consume the data in another action:

string userName = TempData["userName"].ToString();

TempData can only pass the value between actions that are in the same controller. And it has a one-off feature, which means when the data has been consumed, it will be disposed immediately.

Reference: http://www.cnblogs.com/hangwei/p/4466856.html

2 comments

  1. Thanks for this web. I definitely agree with what you are saying.

  2. I was curious if you ever thought of changing the page layout of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two pictures. Maybe you could space it out better?

Leave a Reply

Your email address will not be published.