MVC传值

Controller ==> View

1.ViewBag

controller:

public ActionResult Index()
{
            var students=new List<string>{
                "Zhang",
                "Li",
                "Wang"
            };
            ViewBag.students = students;
            return View();
}

View:

@foreach (var s in ViewBag.students)
{
            <tr>
                <td>
                    @s
                </td>
            </tr>
}



2.ViewData

controller:

public ActionResult Index()
{
    //var music = me.Album.ToList();
      var students=new List<string>{
                "Zhang",
                "Li",
                "Wang"
      };
      ViewData["Students"] = students;
      return View();
}
View:
        @foreach (var s in (List<string>)ViewData["Students"])
        {
            <tr>
                <td>
                    @s
                </td>
            </tr>
        }



Controller ==> Controller
3.TempData

TempData可以在不同action中传递一次,而ViewData、ViewBag在跳转后就会变成null。下面是TempData的用法示例:

 public ActionResult Index()
        {
            string students = "xsaf";
            TempData["Students"] = students.ToString();
            return View();
        }
        public ActionResult Page()
        {
            var students = TempData["Students"];
            Response.Write(students);
            return View();
        }



利用“?”参数传值


ActionLink


View:

@Html.ActionLink("linkText", "actionName", "controllerName")

@Html.ActionLink("链接", "Index", "Home") 等于 <a href="Home/Index">链接</a>




@Html.ActionLink("linkText", "actionName", "controllerName", routeValues, htmlAttributes)

@Html.ActionLink("链接", "Index", "Login", new{ code=123 }, new{target="_blank"} )
 
 
 
 
controller:
public ActionResult Login(int code)
{
       int CCode=code;    //直接获取到code的值为123.	
       return View();
}
 
 












猜你喜欢

转载自blog.csdn.net/jos1n/article/details/78370188