我开始使用 MVC,目前正在开发一个应用程序。当我试图将一些数据从视图传递到控制器操作时,我遇到了一个小问题。
这是我的模型:
public class TicketIndexModel
{
public IEnumerable<Ticket> ticketList { get; set; }
public Ticket newTicket { get; set; }
}
这是我的控制器动作:
public ActionResult AddTicket(Ticket ticket)
{
string user = User.Identity.Name;
TicketDetail ticketDetails = new TicketDetail();
if (ModelState.IsValid)
{
ticket.DateCreated = DateTime.Now;
ticket.Status = "submitted";
ticket.UserName = user;
db.Tickets.Add(ticket);
db.SaveChanges();
//some other stuff
return RedirectToAction("Index");
}
在视图中,首先我显示所有票,然后我有一个小表格来添加新票。这就是表格的样子。
@using (Html.BeginForm("AddTicket","Ticket",FormMethod.Post)) {
<div class="editor-label">
@Html.LabelFor(model => model.newTicket.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.newTicket.Title)
@Html.ValidationMessageFor(model => model.newTicket.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.newTicket.Description)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.newTicket.Description, new { rows= "8",cols="2"})
@Html.ValidationMessageFor(model => model.newTicket.Description)
</div>
<p>
<input type="submit" value="Submit" />
</p>
}
我面临的问题是当我尝试添加新票时,票证参数始终为空,因此 If(ModelState.Isvalid) <- 始终为假,因此我无法向数据库添加新票证。
有谁知道为什么?
稍后编辑:
我的模型现在是:
public IPagedList<Ticket> ticketList { get; set; }
//[Required(ErrorMessage ="Title required")]
[Display(Name = "Title")]
public string TicketTitle { get; set; }
//[Required(ErrorMessage="Description Required")]
[Display(Name = "Description")]
public string TicketDescription { get; set; }
我现在的方法是:
[HttpPost]
public ActionResult AddTicket(TicketIndexModel newTicket)
{
string user = User.Identity.Name;
Ticket ticket = new Ticket();
if (ModelState.IsValid)
{
ticket.Title = newTicket.TicketTitle;
ticket.Description = newTicket.TicketDescription;
ticket.DateCreated = DateTime.Now;
ticket.Status = "open";
ticket.UserName = user;
db.Tickets.Add(ticket);
db.SaveChanges();
我现在遇到的问题如下:
如果在模型中,我评论 [Required] 我可以添加一张票,如果没有,在控制器中,每次我提交新票时签名中的 newTicket 为空。但是,控制器输入 if(ModelState.IsValid) 并且我在 db.SaveChanges(ticket) 处收到错误。
我需要服务器和客户端验证。你能帮助我吗 ?