我正在做备忘录Web应用程序。MVC3(剃刀)通过模型数据
和主页面包含'创建和列表和修改'功能。
但我不知道如何从控制器传递模型(用于创建)和列表(用于列表)以查看(剃刀)。
这是我的笔记型号,
[Table("note")]
public class Note
{
[Key]
public int id { get; set; }
[Required(ErrorMessage="Content is required")]
[DisplayName("Note")]
public string content { get; set; }
public DateTime date { get; set; }
[Required(ErrorMessage = "User ID is required")]
[DisplayName("User ID")]
public string userId {get; set;}
public Boolean isPrivate { get; set; }
public virtual ICollection<AttachedFile> AttachedFiles { get; set; }
}
我试过,
1)
public ActionResult Index()
{
var notes = unitOfWork.NoteRepository.GetNotes();
return View(notes);
}
然后,在视图,
@model Enumerable<MemoBoard.Models.Note>
//I can not use this, because the model is Enumerable type
@Html.LabelFor(model => model.userId)
所以,我做了视图模型
2)
public class NoteViewModel
{
public IEnumerable<Note> noteList { get; set; }
public Note note { get; set; }
}
在控制器,
public ActionResult Index()
{
var notes = unitOfWork.NoteRepository.GetNotes();
return View(new NoteViewModel(){noteList=notes.ToList(), note = new Note()});
}
和在View,
@model MemoBoard.Models.NoteViewModel
@Html.LabelFor(model => model.note.userId)
它看起来很好,但在源视图,它显示
<input data-val="true" data-val-required="User ID is required" id="note_userId" name="note.userId" type="text" value="" />
的名字是note.userId不是userId。
列举这种情况,我应该怎么做才能工作?
请指教我。
感谢
[编辑] (首先,感谢所有建议)
然后,我怎样才能改变这种控制器
[HttpPost]
public ActionResult Index(Note note)
{
try
{
if (ModelState.IsValid)
{
unitOfWork.NoteRepository.InsertNote(note);
unitOfWork.Save();
return RedirectToAction("Index");
}
}catch(DataException){
ModelState.AddModelError("", "Unable to save changes. Try again please");
}
return RedirectToAction("Index");
}
如果我改变参数类型NoteViewModel,那么我应该如何做有效的检查?
[HttpPost]
public ActionResult Index(NoteViewModel data)
{
try
{
if (ModelState.IsValid) <===
在regar d对于情况2,可以有一个名为note的字段。userId,只要您使用相同(或类似的结构化)视图模型来接收回发。模型绑定器将负责绑定字段... –
@Jan Hansen感谢您的评论,请您再次查看我编辑过的问题吗?我需要更多的帮助^^ –
由于webdeveloper在下面的回答中提到了注释,RedirectToAction清除了视图模型的状态,因此当存在模型错误时,您应该使用**返回View()**。除此之外,ModelState.IsValid应该可以正常工作,将NoteViewModel作为您的操作方法的输入... –