我是 .net 的新手,我正在使用 MVC5,我检查了一些 .net 示例,其中人们正在执行强类型视图以将数据从控制器传递到视图。为此,您应该有一个模型来设置这些参数,然后您可以传递数据。
假设我的模型是用户
namespace Mvc5Application.Models{
using System;
using System.Collections.Generic;
public partial class User
{
public System.Guid UserID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public Nullable<System.Guid> OrgID { get; set; }
public virtual Organization Organization { get; set; }
}
}
现在我的控制器是 Home 并且在索引页面中有一个登录页面
如果您使用传统方式,那么您的控制器将看起来像
[AllowAnonymous]
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
[HttpPost]
public ActionResult Index(User model)
{
...[code for verification ]...
return View(model);
}
而对应的视图将是
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.username)
</td>
<td>
@Html.DisplayFor(modelItem => item.password)
</td>
</tr>
}
但是,如果您正在考虑进行一些自定义,例如,如果您不想遵循这种传统模式,并且想从视图页面发布任何内容,然后将其放入控制器并在执行某些操作后,如果您有一组数据并且您想将数据传递给查看并在视图中的不同位置显示它,那么您必须使用 ViewBag 或 ViewData
那么控制器将是
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
String Username = form["Username"].ToString();
String Password = form["Password"].ToString();
Dictionary<string, string> MyList = new Dictionary<String, String>();
MyList.Add("name",Username);
MyList.Add("pass",Password);
ViewData["user"] = MyList;
return View();
}
视图将是
@{
ViewBag.Title = "Home Page";
var list = ViewData["user"] as Dictionary<String, String>;
}
<h2>@ViewBag.Message</h2>
<div>
@if (list != null)
{
@Html.Label("User:-") @list["name"]
<br />@Html.Label("password:-") @list["pass"]
}
</div>
<p>
Please ligin / Register from here</p>
@using (Html.BeginForm("Home"))
{
<table>
<tr>
<td>User Name</td>
<td>@Html.TextBox("Username", ViewBag.CurrentFilter as string)</td>
</tr>
<tr>
<td>Password</td>
<td>@Html.TextBox("Password", ViewBag.CurrentFilter as string)</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" class="btn btn-default" /></td>
</tr>
</table>
}