I wanna try to make this is as simple as possible.
Lets say I have a Project Model and a Task Model
I want to create a Project with 3 tasks assigned to that project in one single form
Whats the best way to do this??
Would the method simply receive a Project or what else do i need to have there.. will just saving the project (in repository) also save the related tasks?...
In the view... do i need a viewModel.. Im confused. please help
public ActionResult Create(Project p){
}
Here's how I would proceed:
public class TaskViewModel
{
public string Name { get; set; }
}
public class ProjectViewModel
{
public string ProjectName { get; set; }
public IEnumerable<TaskViewModel> Tasks { get; set; }
}
then have a controller:
public class ProjectsController: Controller
{
public ActionResult Index()
{
var project = new ProjectViewModel
{
// Fill the collection with 3 tasks
Tasks = Enumerable.Range(1, 3).Select(x => new TaskViewModel())
};
return View(project);
}
[HttpPost]
public ActionResult Index(ProjectViewModel project)
{
if (!ModelState.IsValid)
{
// The user didn't fill all required fields =>
// redisplay the form with validation error messages
return View(project);
}
// TODO: do something with the model
// You could use AutoMapper here to map
// the view model back to a model which you
// would then pass to your repository for persisting or whatever
// redirect to some success action
return RedirectToAction("Success", "Home");
}
}
and then the view (~/Views/Projects/Create.cshtml):
#model AppName.Models.ProjectViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.ProjectName)
#Html.EditorFor(x => x.ProjectName)
#Html.ValidationMessageFor(x => x.ProjectName)
</div>
#Html.EditorFor(x => x.Tasks)
<input type="submit" value="Create!" />
}
and the corresponding task editor template (~/Views/Projects/EditorTemplates/TaskViewModel.cshtml):
#model AppName.Models.TaskViewModel
<div>
#Html.LabelFor(x => x.Name)
#Html.EditorFor(x => x.Name)
#Html.ValidationMessageFor(x => x.Name)
</div>
Add a collection of Task models to the Project model, and use a foreach loop to display the tasks, or repeat a partial view that knows how to display a single task.
Related
I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.
e.g.
public class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
}
public class RegisterViewModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Do I need to make another ViewModel which holds these 2 ViewModels?
public BigViewModel
{
public LoginViewModel LoginViewModel{get; set;}
public RegisterViewModel RegisterViewModel {get; set;}
}
I need the validation attributes to be brought forward to the view. This is why I need the ViewModels.
Isn't there another way such as (without the BigViewModel):
#model ViewModel.RegisterViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Name)
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
#model ViewModel.LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
There are lots of ways...
with your BigViewModel
you do:
#model BigViewModel
#using(Html.BeginForm()) {
#Html.EditorFor(o => o.LoginViewModel.Email)
...
}
you can create 2 additional views
Login.cshtml
#model ViewModel.LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
and register.cshtml same thing
after creation you have to render them in the main view and pass them the viewmodel/viewdata
so it could be like this:
#{Html.RenderPartial("login", ViewBag.Login);}
#{Html.RenderPartial("register", ViewBag.Register);}
or
#{Html.RenderPartial("login", Model.LoginViewModel)}
#{Html.RenderPartial("register", Model.RegisterViewModel)}
using ajax parts of your web-site become more independent
iframes, but probably this is not the case
I'd recommend using Html.RenderAction and PartialViewResults to accomplish this; it will allow you to display the same data, but each partial view would still have a single view model and removes the need for a BigViewModel
So your view contain something like the following:
#Html.RenderAction("Login")
#Html.RenderAction("Register")
Where Login & Register are both actions in your controller defined like the following:
public PartialViewResult Login( )
{
return PartialView( "Login", new LoginViewModel() );
}
public PartialViewResult Register( )
{
return PartialView( "Register", new RegisterViewModel() );
}
The Login & Register would then be user controls residing in either the current View folder, or in the Shared folder and would like something like this:
/Views/Shared/Login.cshtml: (or /Views/MyView/Login.cshtml)
#model LoginViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
/Views/Shared/Register.cshtml: (or /Views/MyView/Register.cshtml)
#model ViewModel.RegisterViewModel
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(model => model.Name)
#Html.TextBoxFor(model => model.Email)
#Html.PasswordFor(model => model.Password)
}
And there you have a single controller action, view and view file for each action with each totally distinct and not reliant upon one another for anything.
Another way is to use:
#model Tuple<LoginViewModel,RegisterViewModel>
I have explained how to use this method both in the view and controller for another example: Two models in one view in ASP MVC 3
In your case you could implement it using the following code:
In the view:
#using YourProjectNamespace.Models;
#model Tuple<LoginViewModel,RegisterViewModel>
#using (Html.BeginForm("Login1", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple => tuple.Item2.Name, new {#Name="Name"})
#Html.TextBoxFor(tuple => tuple.Item2.Email, new {#Name="Email"})
#Html.PasswordFor(tuple => tuple.Item2.Password, new {#Name="Password"})
}
#using (Html.BeginForm("Login2", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple => tuple.Item1.Email, new {#Name="Email"})
#Html.PasswordFor(tuple => tuple.Item1.Password, new {#Name="Password"})
}
Note that I have manually changed the Name attributes for each property when building the form. This needs to be done, otherwise it wouldn't get properly mapped to the method's parameter of type model when values are sent to the associated method for processing. I would suggest using separate methods to process these forms separately, for this example I used Login1 and Login2 methods. Login1 method requires to have a parameter of type RegisterViewModel and Login2 requires a parameter of type LoginViewModel.
if an actionlink is required you can use:
#Html.ActionLink("Edit", "Edit", new { id=Model.Item1.Id })
in the controller's method for the view, a variable of type Tuple needs to be created and then passed to the view.
Example:
public ActionResult Details()
{
var tuple = new Tuple<LoginViewModel, RegisterViewModel>(new LoginViewModel(),new RegisterViewModel());
return View(tuple);
}
or you can fill the two instances of LoginViewModel and RegisterViewModel with values and then pass it to the view.
Use a view model that contains multiple view models:
namespace MyProject.Web.ViewModels
{
public class UserViewModel
{
public UserDto User { get; set; }
public ProductDto Product { get; set; }
public AddressDto Address { get; set; }
}
}
In your view:
#model MyProject.Web.ViewModels.UserViewModel
#Html.LabelFor(model => model.User.UserName)
#Html.LabelFor(model => model.Product.ProductName)
#Html.LabelFor(model => model.Address.StreetName)
Do I need to make another view which holds these 2 views?
Answer:No
Isn't there another way such as (without the BigViewModel):
Yes, you can use Tuple (brings magic in view having multiple model).
Code:
#model Tuple<LoginViewModel, RegisterViewModel>
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple=> tuple.Item.Name)
#Html.TextBoxFor(tuple=> tuple.Item.Email)
#Html.PasswordFor(tuple=> tuple.Item.Password)
}
#using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
#Html.TextBoxFor(tuple=> tuple.Item1.Email)
#Html.PasswordFor(tuple=> tuple.Item1.Password)
}
Add this ModelCollection.cs to your Models
using System;
using System.Collections.Generic;
namespace ModelContainer
{
public class ModelCollection
{
private Dictionary<Type, object> models = new Dictionary<Type, object>();
public void AddModel<T>(T t)
{
models.Add(t.GetType(), t);
}
public T GetModel<T>()
{
return (T)models[typeof(T)];
}
}
}
Controller:
public class SampleController : Controller
{
public ActionResult Index()
{
var model1 = new Model1();
var model2 = new Model2();
var model3 = new Model3();
// Do something
var modelCollection = new ModelCollection();
modelCollection.AddModel(model1);
modelCollection.AddModel(model2);
modelCollection.AddModel(model3);
return View(modelCollection);
}
}
The View:
enter code here
#using Models
#model ModelCollection
#{
ViewBag.Title = "Model1: " + ((Model.GetModel<Model1>()).Name);
}
<h2>Model2: #((Model.GetModel<Model2>()).Number</h2>
#((Model.GetModel<Model3>()).SomeProperty
a simple way to do that
we can call all model first
#using project.Models
then send your model with viewbag
// for list
ViewBag.Name = db.YourModel.ToList();
// for one
ViewBag.Name = db.YourModel.Find(id);
and in view
// for list
List<YourModel> Name = (List<YourModel>)ViewBag.Name ;
//for one
YourModel Name = (YourModel)ViewBag.Name ;
then easily use this like Model
My advice is to make a big view model:
public BigViewModel
{
public LoginViewModel LoginViewModel{get; set;}
public RegisterViewModel RegisterViewModel {get; set;}
}
In your Index.cshtml, if for example you have 2 partials:
#addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers
#model .BigViewModel
#await Html.PartialAsync("_LoginViewPartial", Model.LoginViewModel)
#await Html.PartialAsync("_RegisterViewPartial ", Model.RegisterViewModel )
and in controller:
model=new BigViewModel();
model.LoginViewModel=new LoginViewModel();
model.RegisterViewModel=new RegisterViewModel();
I want to say that my solution was like the answer provided on this stackoverflow page: ASP.NET MVC 4, multiple models in one view?
However, in my case, the linq query they used in their Controller did not work for me.
This is said query:
var viewModels =
(from e in db.Engineers
select new MyViewModel
{
Engineer = e,
Elements = e.Elements,
})
.ToList();
Consequently, "in your view just specify that you're using a collection of view models" did not work for me either.
However, a slight variation on that solution did work for me. Here is my solution in case this helps anyone.
Here is my view model in which I know I will have just one team but that team may have multiple boards (and I have a ViewModels folder within my Models folder btw, hence the namespace):
namespace TaskBoard.Models.ViewModels
{
public class TeamBoards
{
public Team Team { get; set; }
public List<Board> Boards { get; set; }
}
}
Now this is my controller. This is the most significant difference from the solution in the link referenced above. I build out the ViewModel to send to the view differently.
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TeamBoards teamBoards = new TeamBoards();
teamBoards.Boards = (from b in db.Boards
where b.TeamId == id
select b).ToList();
teamBoards.Team = (from t in db.Teams
where t.TeamId == id
select t).FirstOrDefault();
if (teamBoards == null)
{
return HttpNotFound();
}
return View(teamBoards);
}
Then in my view I do not specify it as a list. I just do "#model TaskBoard.Models.ViewModels.TeamBoards" Then I only need a for each when I iterate over the Team's boards. Here is my view:
#model TaskBoard.Models.ViewModels.TeamBoards
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Team</h4>
<hr />
#Html.ActionLink("Create New Board", "Create", "Board", new { TeamId = #Model.Team.TeamId}, null)
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => Model.Team.Name)
</dt>
<dd>
#Html.DisplayFor(model => Model.Team.Name)
<ul>
#foreach(var board in Model.Boards)
{
<li>#Html.DisplayFor(model => board.BoardName)</li>
}
</ul>
</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.Team.TeamId }) |
#Html.ActionLink("Back to List", "Index")
</p>
I am fairly new to ASP.NET MVC so it took me a little while to figure this out. So, I hope this post helps someone figure it out for their project in a shorter timeframe. :-)
Create one new class in your model and properties of LoginViewModel and RegisterViewModel:
public class UserDefinedModel()
{
property a1 as LoginViewModel
property a2 as RegisterViewModel
}
Then use UserDefinedModel in your view.
you can always pass the second object in a ViewBag or View Data.
This is a simplified example with IEnumerable.
I was using two models on the view: a form with search criteria (SearchParams model), and a grid for results, and I struggled with how to add the IEnumerable model and the other model on the same view. Here is what I came up with, hope this helps someone:
#using DelegatePortal.ViewModels;
#model SearchViewModel
#using (Html.BeginForm("Search", "Delegate", FormMethod.Post))
{
Employee First Name
#Html.EditorFor(model => model.SearchParams.FirstName,
new { htmlAttributes = new { #class = "form-control form-control-sm " } })
<input type="submit" id="getResults" value="SEARCH" class="btn btn-primary btn-lg btn-block" />
}
<br />
#(Html
.Grid(Model.Delegates)
.Build(columns =>
{
columns.Add(model => model.Id).Titled("Id").Css("collapse");
columns.Add(model => model.LastName).Titled("Last Name");
columns.Add(model => model.FirstName).Titled("First Name");
})
...
)
SearchViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchViewModel
{
public IEnumerable<DelegatePortal.Models.DelegateView> Delegates { get; set; }
public SearchParamsViewModel SearchParams { get; set; }
....
DelegateController.cs:
// GET: /Delegate/Search
public ActionResult Search(String firstName)
{
SearchViewModel model = new SearchViewModel();
model.Delegates = db.Set<DelegateView>();
return View(model);
}
// POST: /Delegate/Search
[HttpPost]
public ActionResult Search(SearchParamsViewModel searchParams)
{
String firstName = searchParams.FirstName;
SearchViewModel model = new SearchViewModel();
if (firstName != null)
model.Delegates = db.Set<DelegateView>().Where(x => x.FirstName == firstName);
return View(model);
}
SearchParamsViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchParamsViewModel
{
public string FirstName { get; set; }
}
}
I have a Register Primary View which shows two different types of Addresses 1. Home Address 2. Mailing Address
public class RegisterModel
{
public AddressModel HomeAddress { get; set; }
public AddressModel MailAddress { get; set; }
}
public class AddressModel
{
public string Street1 { get; set; }
public string Street2 { get; set; }
public string State { get; set; }
public string City { get; set; }
}
My main Register View is Strongly Typed to RegisterModel as follows
#model MyNamespace.Models.RegisterModel
#{
Layout = "~/Views/_Layout.cshtml";
}
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
#Html.Action("MyAddressPartial")
#Html.Action("MyAddressPartial")
</div>
}
MyAddressPartialView as follows : -
#model MyNamespace.Models.AddressModel
#{
Layout = "~/Views/_Layout.cshtml";
}
<div id="Address">
#Html.TextBoxFor(m=>m.Street1 ,new { #id="Street1 "})
#Html.TextBoxFor(m=>m.Street2,new { #id="Street2"})
#Html.TextBoxFor(m=>m.State ,new { #id="State "})
#Html.TextBoxFor(m=>m.City,new { #id="City"})
</div>
My RegisterController:-
// Have to instantiate the strongly Typed partial view when my form first loads
// and then pass it as parameter to "Register" post action method.
// As you can see the #Html.Action("MyAddressPartial") above in main
// Register View calls this.
public ActionResult MyAddressPartial()
{
return PartialView("MyAddressPartialView", new AddressModel());
}
I submit my Main Form to below mentioned action method in same Register Controller.
[HttpPost]
public ActionResult Register(RegisterModel model,
AddressModel homeAddress,
AddressModel mailingAddress)
{
//I want to access homeAddress and mailingAddress contents which should
//be different, but as if now it comes same.
}
I don't want to create a separate class one for MailingAddress and one for HomeAddress. if I do that then I will have to create two separate strongly typed partial views one for each address.
Any ideas on how to reuse the classes and partial views and make them dynamic and read their separate values in Action Method Post.
Edit 1 Reply to scott-pascoe:-
In DisplayTemplates Folder, I added following AddressModel.cshtml
<div>
#Html.DisplayFor(m => m.Street1);
#Html.DisplayFor(m => m.Street2);
#Html.DisplayFor(m => m.State);
#Html.DisplayFor(m => m.City);
</div>
Also In EditorTemplate Folder, I added following AddressModel.cshtml but with EditorFor
<div>
#Html.EditorFor(m => m.Street1);
#Html.EditorFor(m => m.Street2);
#Html.EditorFor(m => m.State);
#Html.EditorFor(m => m.City);
</div>
Now how do i use them in RegisterView and also how i read values in Controller's post Action Method ? What else would have to be modified ? I have added almost entire code above. I am pretty beginner to MVC.
The typical ASP.NET MVC method for doing this is to use EditorTemplates and DisplayTemplates for your custom types.
In ~/Views/Shared, Create two folders, DisplayTemplates, and EditorTemplates.
In the DisplayTemplates folder create a partial view with the name of your Model, ie (AddressModel), and create a DisplayFor Template.
In the EditorTemplates folder create another partial view named AddressModel.cshtml and create an EditorFor Template.
MVC will then automatically use your templates and give you the data that you are asking for.
Use #Html.EditorFor (or #Html.DisplayFor, for display) in your view:
#model MyNamespace.Models.RegisterModel
#{
Layout = "~/Views/_Layout.cshtml";
}
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
<div id="form">
#Html.EditorFor(m => m.HomeAddress)
#Html.EditorFor(m => MailAddress)
</div>
}
You will not need to have a separate controller action for the parts, just populate the addresses in the RegisterModel before in your controller. Like this:
[HttpGet]
public ActionResult Register() // this will be the page people see first
{
var model = new RegisterModel();
return View(model); // assuming your view is called Register.cshtml
}
[HttpPost]
public ActionResult Register(RegisterModel model){
DosomethingWithHomeAddress(model.HomeAddress);
DosomethingWithMailAddress(model.MailAddress);
model.IsSaved = true; // some way to let the user knwo that save was successful;
// if this is true, display a paragraph on the view
return View(model);
}
In Short: How do I successfully edit a DB entry without needing to include every single field for the Model inside of the Edit View?
UPDATE
So I have an item in the DB (an Article). I want to edit an article. The article I edit has many properties (Id, CreatedBy, DateCreated, Title, Body). Some of these properties never need to change (like Id, CreatedBy, DateCreated). So in my Edit View, I only want input fields for fields that can be changed (like Title, Body). When I implement an Edit View like this, Model Binding fails. Any fields that I didn't supply an input for gets set to some 'default' value (like DateCreated gets set to 01/01/0001 12:00:00am). If I do supply inputs for every field, everything works fine and the article is edited as expected. I don't know if it's correct in saying that "Model Binding fails" necessarily, so much as that "the system fills in fields with incorrect data if no Input field was supplied for them in the Edit View."
How can I create an Edit View in such a way that I only need to supply input fields for fields that can/need editing, so that when the Edit method in the Controller is called, fields such as DateCreated are populated correctly, and not set to some default, incorrect value? Here is my Edit method as it currently stands:
[HttpPost]
public ActionResult Edit(Article article)
{
// Get a list of categories for dropdownlist
ViewBag.Categories = GetDropDownList();
if (article.CreatedBy == (string)CurrentSession.SamAccountName || (bool)CurrentSession.IsAdmin)
{
if (ModelState.IsValid)
{
article.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
article.LastUpdated = DateTime.Now;
article.Body = Sanitizer.GetSafeHtmlFragment(article.Body);
_db.Entry(article).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(article);
}
// User not allowed to edit
return RedirectToAction("Index", "Home");
}
And the Edit View if it helps:
. . .
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Article</legend>
<p>
<input type="submit" value="Save" /> | #Html.ActionLink("Back to List", "Index")
</p>
#Html.Action("Details", "Article", new { id = Model.Id })
#Html.HiddenFor(model => model.CreatedBy)
#Html.HiddenFor(model => model.DateCreated)
<div class="editor-field">
<span>
#Html.LabelFor(model => model.Type)
#Html.DropDownListFor(model => model.Type, (SelectList)ViewBag.Categories)
#Html.ValidationMessageFor(model => model.Type)
</span>
<span>
#Html.LabelFor(model => model.Active)
#Html.CheckBoxFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active)
</span>
<span>
#Html.LabelFor(model => model.Stickied)
#Html.CheckBoxFor(model => model.Stickied)
#Html.ValidationMessageFor(model => model.Stickied)
</span>
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
#* We set the id of the TextArea to 'CKeditor' for the CKeditor script to change the TextArea into a WYSIWYG editor. *#
#Html.TextAreaFor(model => model.Body, new { id = "CKeditor", #class = "text-editor" })
#Html.ValidationMessageFor(model => model.Body)
</div>
</fieldset>
. . .
If I were to leave out these two inputs:
#Html.HiddenFor(model => model.CreatedBy)
#Html.HiddenFor(model => model.DateCreated)
when the Edit method is called, they're set to default values. CreatedBy is set to Null, Created is set to 01/01/0001 12:00:00am
Why are they not set to the values as they are currently set to in the DB?
After yet some more research I came upon some tools that assist in the ViewModel process - one being AutoMapper & the other InjectValues. I went with InjectValues primarily because it can not only "flatten" objects (map object a -> b) but it can also "unflatten" them (map object b -> a) - something that AutoMapper unfortunately lacks out-of-the-box - something I need to do in order to update values inside of a DB.
Now, instead of sending my Article model with all of its properties to my views, I created an ArticleViewModel containing only the following properties:
public class ArticleViewModel
{
public int Id { get; set; }
[MaxLength(15)]
public string Type { get; set; }
public bool Active { get; set; }
public bool Stickied { get; set; }
[Required]
[MaxLength(200)]
public string Title { get; set; }
[Required]
[AllowHtml]
public string Body { get; set; }
}
When I Create an Article, instead of sending an Article object (with every property) I send the View a 'simpler' model - my ArticleViewModel:
//
// GET: /Article/Create
public ActionResult Create()
{
return View(new ArticleViewModel());
}
For the POST method we take the ViewModel we sent to the View and use its data to Create a new Article in the DB. We do this by "unflattening" the ViewModel onto an Article object:
//
// POST: /Article/Create
public ActionResult Create(ArticleViewModel articleViewModel)
{
Article article = new Article(); // Create new Article object
article.InjectFrom(articleViewModel); // unflatten data from ViewModel into article
// Fill in the missing pieces
article.CreatedBy = CurrentSession.SamAccountName; // Get current logged-in user
article.DateCreated = DateTime.Now;
if (ModelState.IsValid)
{
_db.Articles.Add(article);
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
ViewBag.Categories = GetDropDownList();
return View(articleViewModel);
}
The "missing pieces" filled in are Article properties I didn't want to set in the View, nor do they need to be updated in the Edit view (or at all, for that matter).
The Edit method is pretty much the same, except instead of sending a fresh ViewModel to the View we send a ViewModel pre-populated with data from our DB. We do this by retrieving the Article from the DB and flattening the data onto the ViewModel. First, the GET method:
//
// GET: /Article/Edit/5
public ActionResult Edit(int id)
{
var article = _db.Articles.Single(r => r.Id == id); // Retrieve the Article to edit
ArticleViewModel viewModel = new ArticleViewModel(); // Create new ArticleViewModel to send to the view
viewModel.InjectFrom(article); // Inject ArticleViewModel with data from DB for the Article to be edited.
return View(viewModel);
}
For the POST method we want to take the data sent from the View and update the Article stored in the DB with it. To do this we simply reverse the flattening process by 'unflattening' the ViewModel onto the Article object - just like we did for the POST version of our Create method:
//
// POST: /Article/Edit/5
[HttpPost]
public ActionResult Edit(ArticleViewModel viewModel)
{
var article = _db.Articles.Single(r => r.Id == viewModel.Id); // Grab the Article from the DB to update
article.InjectFrom(viewModel); // Inject updated values from the viewModel into the Article stored in the DB
// Fill in missing pieces
article.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
article.LastUpdated = DateTime.Now;
if (ModelState.IsValid)
{
_db.Entry(article).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(viewModel); // Something went wrong
}
We also need to change the strongly-typed Create & Edit views to expect an ArticleViewModel instead of an Article:
#model ProjectName.ViewModels.ArticleViewModel
And that's it!
So in summary, you can implement ViewModels to pass just pieces of your Models to your Views. You can then update just those pieces, pass the ViewModel back to the Controller, and use the updated information in the ViewModel to update the actual Model.
View model example:
public class ArticleViewModel {
[Required]
public string Title { get; set; }
public string Content { get; set; }
}
Binding example
public ActionResult Edit(int id, ArticleViewModel article) {
var existingArticle = db.Articles.Where(a => a.Id == id).First();
existingArticle.Title = article.Title;
existingArticle.Content = article.Content;
db.SaveChanges();
}
That is simple example, but you should look at ModelState to check if model doesn't have errors, check authorization and move this code out of controller to service classes, but
that is another lesson.
This is corrected Edit method:
[HttpPost]
public ActionResult Edit(Article article)
{
// Get a list of categories for dropdownlist
ViewBag.Categories = GetDropDownList();
if (article.CreatedBy == (string)CurrentSession.SamAccountName || (bool)CurrentSession.IsAdmin)
{
if (ModelState.IsValid)
{
var existingArticle = _db.Articles.First(a => a.Id = article.Id);
existingArticle.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
existingArticle.LastUpdated = DateTime.Now;
existingArticle.Body = Sanitizer.GetSafeHtmlFragment(article.Body);
existingArticle.Stickied = article.Stickied;
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(article);
}
// User not allowed to edit
return RedirectToAction("Index", "Home");
}
another good way without viewmodel
// POST: /Article/Edit/5
[HttpPost]
public ActionResult Edit(Article article0)
{
var article = _db.Articles.Single(r => r.Id == viewModel.Id); // Grab the Article from the DB to update
article.Stickied = article0.Stickied;
// Fill in missing pieces
article.LastUpdatedBy = MyHelpers.SessionBag.Current.SamAccountName;
article.LastUpdated = DateTime.Now;
if (ModelState.IsValid)
{
_db.Entry(article0).State = EntityState.Unchanged;
_db.Entry(article).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(article0); // Something went wrong
}
Use ViewModels.
Through my continued research of finding a solution to this issue I believe that using these things called "ViewModels" is the way to go. As explained in a post by Jimmy Bogard, ViewModels are a way to "show a slice of information from a single entity."
asp.net-mvc-view-model-patterns got me headed on the right track; I'm still checking out some of the external resources the author posted in order to further grasp the ViewModel concept (The blog post by Jimmy being one of them).
In addition to the answer, AutoMapper can also be used to unflatten it.
Using AutoMapper to unflatten a DTO
I am presently working on a application in which I have a display a list of items in a list box in the view and then send back the selected items to the controller.
My model is as follows:
public class Items
{
[DisplayName("Items")]
public string[] Items { get; set; }
}
When the user first requests the page, the list of items has to be queried from a database and sent to the view.
I am able to figure out how to collect the items into ArrayList/string[] at the controller side but am not able to understand the syntax for binding the view with the model and displaying the list using Html.ListboxFor and sending back the model on form submit.
Can someone please help me.
Thanks.
View model:
public class MyViewModel
{
[DisplayName("Items")]
public string[] SelectedItemIds { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// preselect some items
// leave empty if you want none to be selected initially
SelectedItemIds = new[] { "1", "3" },
// Normally you would fetch those from your database
// hardcoded here for the purpose of the post
Items = Enumerable.Range(1, 10).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = " item " + x
})
};
return View(model);
}
[HttpPost]
public ActionResult Index(string[] selectedItemIds)
{
// here you will get the list of selected item ids
// where you could process them
// If you need to redisplay the same view make sure that
// you refetch the model items once again from the database
...
}
}
View (Razor):
#model AppName.Models.MyViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.SelectedItemIds)
#Html.ListBoxFor(
x => x.SelectedItemIds,
new SelectList(Model.Items, "Value", "Text")
)
<input type="submit" value="OK" />
}
View (WebForms):
<% using (Html.BeginForm()) { %>
<%= Html.LabelFor(x => x.SelectedItemIds) %>
<%= Html.ListBoxFor(
x => x.SelectedItemIds,
new SelectList(Model.Items, "Value", "Text")
) %>
<input type="submit" value="OK" />
<% } %>
I have an ASP.NET MVC 3 (Razor) website, and a (simplified) model called Review:
public class Review
{
public int ReviewId { get; set; }
public bool RecommendationOne
{
// hook property - gets/set values in the ICollection
}
public bool RecommendationTwo { // etc }
public ICollection<Recommendation> Recommendations { get; set; }
}
Recommendation is as follows:
public class Recommendation
{
public byte RecommendationTypeId
}
I also have an enum called RecommendationType, which i use to map the above recommendation to. (based on RecommendationTypeId).
So to summarize - a single Review has many Recommendations, and each of those Recommendations map to a particular enum type, i expose hook properties to simplify model-binding/code.
So, onto the View:
#Html.EditorFor(model => model.Recommendations, "Recommendations")
Pretty simple.
Now, for the editor template, i want to display a checkbox for each possible RecommendationType (enum), and if the model has that recommendation (e.g on edit view), i check the box.
Here's what i have:
#model IEnumerable<xxxx.DomainModel.Core.Posts.Recommendation>
#using xxxx.DomainModel.Core.Posts;
#{
Layout = null;
}
<table>
#foreach (var rec in Enum.GetValues(typeof(RecommendationType)).Cast<RecommendationType>())
{
<tr>
<td>
#* If review contains this recommendation, check the box *#
#if (Model != null && Model.Any(x => x.RecommendationTypeId == (byte)rec))
{
#* How do i create a (checked) checkbox here? *#
}
else
{
#* How do i created a checkbox here? *#
}
#rec.ToDescription()
</td>
</tr>
}
</table>
As the comments suggest - i don't know how to use #Html.CheckBoxFor. Usually that takes an expression based on the model, but i'm how sure how to bind to the hook property based on the currently looped enum value. E.g it needs to dynamically do #Html.CheckBoxFor(x => x.RecommendationOne), #Html.CheckBoxFor(x => x.RecommendationTwo), etc.
The current solution i have (which works), involves manually constructing the <input> (including hidden fields).
But as i'm just getting the hang of editor templates, hoping someone with experience can point me in a "strongly-typed" direction.
Or is there a nicer way (HTML Helper) i can do this?
I would start by introducing a proper view model for the scenario:
public enum RecommendationType { One, Two, Three }
public class ReviewViewModel
{
public IEnumerable<RecommendationViewModel> Recommendations { get; set; }
}
public class RecommendationViewModel
{
public RecommendationType RecommendationType { get; set; }
public bool IsChecked { get; set; }
}
Then the controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: query the repository to fetch your model
// and use AutoMapper to map between it and the
// corresponding view model so that you have a true/false
// for each enum value
var model = new ReviewViewModel
{
Recommendations = new[]
{
new RecommendationViewModel {
RecommendationType = RecommendationType.One,
IsChecked = false
},
new RecommendationViewModel {
RecommendationType = RecommendationType.Two,
IsChecked = true
},
new RecommendationViewModel {
RecommendationType = RecommendationType.Three,
IsChecked = true
},
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(ReviewViewModel model)
{
// Here you will get for each enum value the corresponding
// checked value
// TODO: Use AutoMapper to map back to your model and persist
// using a repository
return RedirectToAction("Success");
}
}
and the corresponding view (~/Views/Home/Index.cshtml):
#model YourAppName.Models.ReviewViewModel
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm())
{
#Html.EditorFor(model => model.Recommendations)
<input type="submit" value="Go" />
}
and finally the editor template (~/Views/Home/EditorTemplates/RecommendationViewModel.cshtml)
#model YourAppName.Models.RecommendationViewModel
<div>
#Html.HiddenFor(x => x.RecommendationType)
#Model.RecommendationType
#Html.CheckBoxFor(x => x.IsChecked)
</div>
Now the view code is cleaned as it should. No ifs, no loops, no LINQ, no reflection, this is the responsibility of the controller/mapper layer. So every time you find yourself writing some advanced C# logic in your view I would recommend you rethinking your view models and adapt them as necessary. That's what view models are intended for: to be as close as possible to the view logic.