我有以下View,Controller和Comment.cs代码,但是我收到错误,
传递到字典中的模型项的类型为“TMPBlog.Models.Comment”,但此字典需要“TMPBlog.Models.Post”类型的模型项。
如果我没有在两个必填文本字段 @ Html.TextBox(“CommentEmail”)和 @ Html.TextArea(“CommentDetail”,new {cols = “65”,rows =“7”}),如果我这样做的话。
控制器代码,
public ActionResult Index(int PostID)
{
Post post = db.Posts.Single(p => p.PostID == PostID);
return View(post);
}
[HttpPost]
public ActionResult Index(Comment comment)
{
if (ModelState.IsValid)
{
string CommentEmail = comment.CommentEmail;
string CommentDetail = comment.CommentDetail;
CommentDetail = CommentDetail.Replace("\n", "<br />");
comment.CommentDetail = CommentDetail;
db.Comments.AddObject(comment);
db.SaveChanges();
return RedirectToAction("CommentResponse", new { id = comment.CommentID });
}
return View(comment);
}
Comment.cs,
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace TMPBlog.Models
{
[MetadataType(typeof(CommentMetaData))]
public partial class Comment
{
}
public class CommentMetaData
{
[Required(ErrorMessage = "You must enter an email address!")]
public object CommentEmail { get; set; }
[Required]
public object CommentDetail { get; set; }
}
}
查看,
@model TMPBlog.Models.Post
@Html.ValidationSummary("There is an error")
@using (Html.BeginForm())
{
@Html.Hidden("CommentDate", String.Format("{0:yyyy-MM-dd HH:mm}", DateTime.Now))
@Html.Hidden("PostCommentFK", @Html.DisplayFor(model => model.PostID))
<br />
<span class="BlueHeading">Add Your Comments Here!</span>
<br /><br />
<div class="editor-label">
Email Address
</div>
<div class="editor-field">
@Html.TextBox("CommentEmail")
@Html.ValidationMessage("CommentEmail", "*")
</div>
<div class="editor-label">
Comments
</div>
<div class="editor-field">
@Html.TextArea("CommentDetail", new { cols = "65", rows = "7" })
@Html.ValidationMessage("CommentDetail", "*")
</div>
<div class="editor-field">
@Html.CheckBox("CommentTicked") Email me when others comment
</div>
<p>
<input type="submit" value="Add Comment" />
</p>
}
我该如何解决这个问题?
干杯,
麦克
答案 0 :(得分:0)
您的视图是TMPBlog.Models.Post
的强类型,但在您的POST控制器操作中,您正在传递评论:
return View(comment);
这显然是错误的。
您只需返回相同的视图:
return View();
由于所有内容都存储在模型状态中,因此将使用相应的错误消息正确地重新显示视图。
还有以下一行:
@Html.Hidden("PostCommentFK", @Html.DisplayFor(model => model.PostID))
可能会简化:
@Html.Hidden("PostCommentFK", Model.PostID)