無論我提交表單,註釋對象只是有一個值Comment Object 但頁面看起來像這樣 Create Form
爲什麼不視圖模型值正確發佈?ASP.NET MVC5 Ajax窗體後置模型null?
public class CommentViewModel{
public Comment comment { get; set; }
public UploadFile Uploadfile { get; set; }
}
這是評論類:
public class Comment{
[Key]
public int Id { get; set; }
public int FileId { get; set; }
public DateTime CreateDate { get; set; }
public string review { get; set; }
public string UserId { get; set; }
}
這是查看:
@using (Ajax.BeginForm(ajaxopts)){
@Html.AntiForgeryToken()
<h4>Comment</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.comment.FileId, htmlAttributes: new { @class = "control-label col-md-2" })
<input class="form-control text-box single-line" data-val="true" data-val-number="The field FileId must be a number." data-val-required="FileId is necessary" id="FileId" name="FileId" type="number" value="@ViewBag.FileId" />
@Html.LabelFor(model => model.comment.CreateDate, htmlAttributes: new { @class = "control-label col-md-2" })
<input class="form-control text-box single-line" data-val="true" data-val-date="The field CreateDate must be a date." data-val-required="CreateDate is necessary" id="CreateDate" name="CreateDate" type="datetime" value="@DateTime.Now.ToString()" />
@Html.LabelFor(model => model.comment.UserId, htmlAttributes: new { @class = "control-label col-md-2" })
<input class="form-control text-box single-line" id="UserId" name="UserId" type="text" value="@User.Identity.Name.ToString()" />
@Html.ValidationMessageFor(model => model.comment.UserId, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.comment.review, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.comment.review, new { htmlAttributes = new { @class = "form-control" } })
<input type="submit" value="Create" class="btn btn-default" />
}
這是控制器:
public ActionResult CreateCommets(Comment comment){
if (ModelState.IsValid)
{
db.Comments.Add(comment);
db.SaveChanges();
}
List<Comment> Commentlist = (from p in db.Comments where p.FileId == comment.FileId select p).ToList();
return PartialView("_CommentsView",Commentlist);
}
有上CreateComments功能A [HttpPost]屬性? –
是的,我在創建問題之前添加它 – CBBing
你能解釋'ajaxopts'嗎? – Usman