我正在做備忘錄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作爲您的操作方法的輸入... –