【发布时间】:2016-09-21 10:24:03
【问题描述】:
我有一个显示帖子详细信息的页面,已识别的用户可以在该帖子上添加评论。
我的问题:
PostID 和 UserID 在 Comment 模型中是 FK,不会从视图传递到控制器
CommnetMessage 为空!!
怎么了?
评论模型:
public class Comment : System.Object
{
public Comment()
{
this.CommnetDate = General.tzIran();
}
[Key]
public int CommentID { get; set; }
[Required]
public string CommnetMessage { get; set; }
[Required]
public DateTime CommnetDate { get; set; }
public string UserId { get; set; }
[Key, ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int PostID { get; set; }
[Key, ForeignKey("PostID")]
public virtual Post posts { get; set; }
}
后模型:
public class Post : System.Object
{
public Post()
{
this.PostDate = General.tzIran();
this.PostViews = 0;
}
[Key]
public int PostID { get; set; }
public string PostName { get; set; }
public string PostSummery { get; set; }
public string PostDesc { get; set; }
public string PostPic { get; set; }
public DateTime PostDate { get; set; }
public int PostViews { get; set; }
public string postMetaKeys { get; set; }
public string PostMetaDesc { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int CategoryID { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public virtual ICollection<Comment> commnets {get; set;}
}
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
/*Realations*/
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
查看模型:
public class PostViewModel
{
public ApplicationUser Users { get; set; }
public Post posts { get; set; }
public Category Categories { get; set; }
public IEnumerable<Comment> ListCommnets { get; set; }
public Comment Commnets { get; set; }
}
控制器:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var post = db.Posts.Find(id);
post.PostViews += 1;
db.SaveChanges();
if (post == null)
{
return HttpNotFound();
}
return View(new PostViewModel() { posts = post });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details([Bind(Include = "CommentID,CommnetMessage,CommnetDate,UserId,PostID")] Comment comment , int? id)
{
int pid = comment.PostID;
if (ModelState.IsValid)
{
db.CommentS.Add(comment);
db.SaveChanges();
TempData["notice"] = "پیغام شما با موفقیت ثبت شد.";
return RedirectToAction("success");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "FirstName", comment.UserId);
ViewBag.PostID = id;
return View( new PostViewModel() { posts = db.Posts.Find(id)});
}
public ActionResult success()
{
ViewBag.Message = "از طریق فرم زیر می توانید برایمان پیغام بگذارید.";
return View("Details", new PostViewModel() { ListCommnets = db.CommentS });
}
评论部分视图:
@using Microsoft.AspNet.Identity
@using FinalKaminet.Models
@using Microsoft.AspNet.Identity.EntityFramework
@model FinalKaminet.ViewModel.PostViewModel
@if (TempData["notice"] != null)
{
<p>@TempData["notice"]</p>
}
@if (Request.IsAuthenticated)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.posts.PostID)
@Html.HiddenFor(model => model.Users.Id)
<div class="form-group">
@Html.LabelFor(model => model.Users.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@{
var name = user.FirstName + " " + user.LastName;
}
<input type="text" id="Id" value="@name" disabled="disabled" class="form-control" />
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Commnets.CommnetMessage, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Commnets.CommnetMessage, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Commnets.CommnetMessage, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
}
}
else
{
<p>@Html.ActionLink("Log in", "Login", "Account", new { returnUrl = Request.Url }, null)</p>
}
【问题讨论】:
-
为什么所有对象都显式继承自 System.Object?
-
您视图中的模型是
PostViewModel,因此您方法中的参数必须匹配-public ActionResult Details( PostViewModel model)。而你使用视图模型,所以删除无意义的[Bind]属性 -
您还应该重新设计您的视图模型。视图模型不应包含在编辑时作为数据模型的属性。它应该只包含视图中需要的那些属性
-
您的视图模型应该只包含 2 个属性
int ID(对于 PostId) andstring comment, and you view should contain onlyEditorFor(m => m.Comment)`(假设您的 ID 将自动绑定)使用默认路由)。数据模型的所有其他值都应在 POST 方法中设置
标签: c# asp.net-mvc entity-framework razor viewmodel