我开始使用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)&lt; - 始终为false,因此我无法向DB添加新票证。
有没有人有任何想法?
稍后修改:
我的模特现在是:
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();
我现在遇到的问题如下:
如果在模型中,我发表评论[必需]我可以在控制器中添加票证(如果没有),每次提交新票证时,签名中的newTicket都为空。但是,控制器输入if(ModelState.IsValid)并在db.SaveChanges(ticket)中收到错误。
我需要服务器和客户端验证。你能救我吗?
答案 0 :(得分:2)
您的AddTicket方法应该如下所示
[HttpPost]
public ActionResult AddTicket(TicketIndexModel ticketIndexModel)
然后从传入其中的对象访问newTicket。