我有一个“查看”页面,在该页面上我获得“用户”的“当前登录用户ID”,日期和页面标题,并将这些值传递给控制器以保存到数据库表中。但是,这些值会将null从视图传递给控制器。我不确定是否可以获取像这样的值并传递给控制器并存储在数据库中。
查看:
@model Sample.Models.UserLog
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Idex", "Index", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<br/>
<br/>
<p >@ViewBag.Title</p>
<P>@User.Identity.Name</P>
<p>@Html.TextBoxFor(model => model.Date, new { @Value = @DateTime.Now.ToShortDateString() })</p>
}
控制器:
public class HomeController : Controller
{
private readonly UserLogEntities _db = new UserLogEntities();
public ActionResult Index([Bind(Include = "Name, Date, Title")] UserLog log)
{
ViewBag.UserName = HttpContext.User.Identity.Name;
if (ModelState.IsValid)
{
_db.UserActivityLogs.Add(log);
_db.Entry(log).State = EntityState.Added;
_db.SaveChanges();
}
return View();
}
}
型号:
public partial class UserLog
{
public string UserName { get; set; }
public string EndPoint { get; set; }
public System.DateTime Date { get; set; }
}
答案 0 :(得分:0)
https://dotnetfiddle.net/AyeU9M
如果在Post Action中放置一个断点,您将看到View中返回的Action中的值 表格
CREATE TABLE [AHCCCS\KXBlau].[UserLog](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserName] [varchar](30) NULL,
[EndPoint] [varchar](30) NULL,
[Date] [datetime] NULL,
CONSTRAINT [PK_UserLog] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
控制器/视图模型
public class UserLogViewModel
{
public string UserName { get; set; }
public string EndPoint { get; set; }
public string Date { get; set; }
}
public class HomeController : Controller
{
private readonly SMARTEntities3 _db = new SMARTEntities3();
[HttpPost]
public ActionResult MyIndex([Bind(Include = "UserName, EndPoint, Date")] UserLogViewModel log)
{
ViewBag.UserName = HttpContext.User.Identity.Name;
if (ModelState.IsValid)
{
//from viewmodel to object
UserLog userLog = new UserLog { Date = DateTime.Parse(log.Date), EndPoint = log.EndPoint,
UserName = log.UserName };
_db.UserLogs.Add(userLog);
_db.Entry(log).State = EntityState.Added;
_db.SaveChanges();
}
return View();
}
public ActionResult Tut142()
{
return View();
}
查看
@model Testy20161006.Controllers.UserLogViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut142</title>
</head>
<body>
@using (Html.BeginForm("MyIndex", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<br />
<br />
<p>@User.Identity.Name</p>
<p>
@*@Html.TextBoxFor(model => model.Date, new { @Value = @DateTime.Now.ToShortDateString() })*@
@Html.LabelFor(model => model.UserName)
@Html.TextBoxFor(model => model.UserName)
</p>
<p>
@Html.LabelFor(model => model.EndPoint)
@Html.TextBoxFor(model => model.EndPoint)
</p>
<p>
@Html.LabelFor(model => model.Date)
@Html.TextBoxFor(model => model.Date)
</p>
<input type="submit" value="Go" />
}
</body>
</html>