I’m making Memo web application.
and the main page contain ‘Create and List and Modify’ functions.
But I don’t know how to pass Model (for create) and List (for List) to View(Razor) from controller.
this is my note model,
[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; }
}
I tried,
1)
public ActionResult Index()
{
var notes = unitOfWork.NoteRepository.GetNotes();
return View(notes);
}
Then, in view,
@model Enumerable<MemoBoard.Models.Note>
//I can not use this, because the model is Enumerable type
@Html.LabelFor(model => model.userId)
So, I made viewModel
2)
public class NoteViewModel
{
public IEnumerable<Note> noteList { get; set; }
public Note note { get; set; }
}
In Controller,
public ActionResult Index()
{
var notes = unitOfWork.NoteRepository.GetNotes();
return View(new NoteViewModel(){noteList=notes.ToList(), note = new Note()});
}
and In View,
@model MemoBoard.Models.NoteViewModel
@Html.LabelFor(model => model.note.userId)
it looks well, BUT in source view, it’s showing
<input data-val="true" data-val-required="User ID is required" id="note_userId" name="note.userId" type="text" value="" />
the name is note.userId not userId.
List this case, how should I do to make working?
Please advice me.
Thanks
[EDIT]
(First of all, thanks for all advices)
Then, How can I change this controller
[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");
}
If I change parameter type to NoteViewModel, then how should I do for valid check?
[HttpPost]
public ActionResult Index(NoteViewModel data)
{
try
{
if (ModelState.IsValid) <===
You can use it in
foreachloop or return list and use it inforloopIt’s normal, this made for model binding
Try this: