Can somebody help me on how to save and update data into multiple entities using a ViewModel?
I have a ViewModel that looks like this:
public class StudentViewModel
{
public Student student;
public StudentAddress studentAddress { get; set; }
public StudentPhoto studentPhoto { get; set; }
// Three entities are related to one to one relationship
public StudentViewModel()
{ }
}
My Controller is:
[HttpPost]
public ActionResult Create(StudentViewModel studentViewModel)
{
if (ModelState.IsValid)
{
return View(studentViewModel);
}
Student s = new Student()
{
Name =studentViewModel.Student.Name,
Speciality = studentViewModel.Student.Speciality,
DateOfReg = studentViewModel.Student.DateOfJoinig,
Qualification = studentViewModel.Student.Qualification,
Email = studentViewModel.Student.Email
};
StudentAddress sa = new StudentAddress()
{
StudentId= studentViewModel.Student.StudentId,
Address = studentViewModel.StudentAddress.Address,
Area = studentViewModell.StudentAddress.Area,
City = studentViewModel.StudentAddress.City,
State = studentViewModel.StudentAddress.State,
Mobile = studentViewModel.StudentAddress.Mobile
};
StudentPhoto sp = new StudentPhoto()
{
StudentId= studentViewModel.Student.StudentId,
Photo = studentViewModel.StudentPhoto.Photo
};
db.Students.Add(s);
db.StudentAddress.Add(sa);
db.StudentPhoto.Add(sp);
db.SaveChanges();
return RedirectToAction("Home");
}
View is:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Doctor</legend>
#Html.EditorFor(model => model.Student.Name )
#Html.EditorFor(model => model.Student.Speciality)
#Html.EditorFor(model => model.Student.DateOfJoinig)
#Html.EditorFor(model => model.Student.Standard)
#Html.HiddenFor(model => model.Student.StudentId)
#Html.EditorFor(model => model.StudentAddress.Address)
#Html.EditorFor(model => model.StudentAddress.Area)
#Html.EditorFor(model => model.StudentAddress.City)
#Html.EditorFor(model => model.StudentAddress.State)
#Html.HiddenFor(model => model.Student.StudentId)
#Html.EditorFor(model => model.StudentPhoto.Photo)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I was able to retrieve and display the data (from multiple entities) into the view. However, now I'm stuck on how can I save and update the above entities with the new data. Most of the examples are 1-1 relationship the mapping is automatic, but in this case the data belongs to multiple entities.
My problem is when i try to save data it redirected to the create page. "ModelState.IsValid" is false always so no data saved. Please help me how do i proceed.
Thanks.
This line at the top of your Action is wrong:
if (ModelState.IsValid)
{
return View(studentViewModel);
}
It should be the opposite, only if the Model is NOT valid, then you should stop the process and re-render the View with the form.
Try:
if (!ModelState.IsValid)
{
return View(studentViewModel);
}
In Controller you check if(modelstate.isvalid) - if is valid you returned view without saving data from view.
The problem with your implementation is that your view model contains a several models(Entities). This is not a good implementation.
Try to create a viewmodel which just contains the fields (flattened version) that you want to be edited by the user when creating a student. Use Data Annotations in your view model like Required or StringLength to validate user inputs.
Related
I have the following entity models:
public class AssetLabel
{
public string QRCode { get; set; }
public string asset { get; set; }
public virtual IEnumerable<Conversation> Conversations { get; set; }
}
public class Conversation
{
public int ID { get; set; }
public virtual AssetLabel AssetLabel{ get; set; }
public string FinderName { get; set; }
public string FinderMobile { get; set; }
public string FinderEmail { get; set; }
public ConversationStatus Status{ get; set; }
public IEnumerable<ConversationMessage> Messages { get; set; }
}
public class ConversationMessage
{
public int ID { get; set; }
public DateTime MessageDateTime { get; set; }
public bool IsFinderMessage { get; set; }
public virtual Conversation Conversation { get; set; }
}
public enum ConversationStatus { open, closed };
public class FinderViewModel : Conversation
{/*used in Controllers->Found*/
}
My MVC application will prompt for a QRCode on a POST request. I then validate this code exists in the database AssetLabel and some other server-side logic is satisfied. I then need to request the user contact details to create a new Conversation record.
Currently I have a GET to a controller action which returns the first form to capture the Code. If this is valid then I create a new FinderViewModel, populate the AssetLabel with the object for the QRCode and return a view to consume the vm and show the fields for the Name, Mobile and Email.
My problem is that although the AssetLabel is being passed to the view as part of the FinderViewModel and I can display fields from the AssetLabel; graphed object the AssetLabel does not get passed back in the POST. I know I could modify the FinderViewModel so that it takes the Conversation as one property and set up the QRCode as a separate property that could be a hidden field in the form and then re-find the the AssetLabel as part of the processing of the second form but this feels like a lot of work seeing as I have already validated it once to get to the point of creating the second form (this is why I am moving away from PHP MVC frameworks).
The first question is HOW?, The second question is am I approaching this design pattern in the wrong way. Is there a more .NETty way to persist the data through multiple forms? At this point in my learning I don't really want to store the information in a cookie or use ajax.
For reference the rest of the code for the 1st form POST, 2nd view and 2nd form POST are shown below (simplified to eliminate irrelevant logic).
public class FoundController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Found
public ActionResult Index()
{
AssetLabel lbl = new AssetLabel();
return View(lbl);
}
[HttpPost]
public ActionResult Index(string QRCode)
{
if (QRCode=="")
{
return Content("no value entered");
}
else
{
/*check to see if code is in database*/
AssetLabel lbl = db.AssetLables.FirstOrDefault(q =>q.QRCode==QRCode);
if (lbl != null)
{
var vm = new FinderViewModel();
vm.AssetLabel = lbl;
vm.Status = ConversationStatus.open;
return View("FinderDetails", vm);
}
else
{/*Label ID is not in the database*/
return Content("Label Not Found");
}
}
}
[HttpPost]
public ActionResult ProcessFinder(FinderViewModel vm)
{
/*
THIS IS WHERE I AM STUCK! - vm.AssetLabel == NULL even though it
was passed to the view with a fully populated object
*/
return Content(vm.AssetLabel.QRCode.ToString());
//return Content("Finder Details posted!");
}
FinderView.cshtml
#model GMSB.ViewModels.FinderViewModel
#{
ViewBag.Title = "TEST FINDER";
}
<h2>FinderDetails</h2>
#using (Html.BeginForm("ProcessFinder","Found",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Finder Details</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.AssetLabel)
<div class="form-group">
#Html.LabelFor(model => model.FinderName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FinderName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FinderName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FinderMobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FinderMobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FinderMobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FinderEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FinderEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FinderEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Rendered HTML snippet for AssetLabel
<input id="AssetLabel" name="AssetLabel" type="hidden"
value="System.Data.Entity.DynamicProxies.AssetLabel_32653C4084FF0CBCFDBE520EA1FC5FE4F22B6D9CD6D5A87E7F1B7A198A59DBB3"
/>
You cannot use #Html.HiddenFor() to generate a hidden output for a complex object. Internally the method use .ToString() to generate the value (in you case the output is System.Data.Entity.DynamicProxies.AssetLabel_32653C4084FF0CBCFDBE520EA1FC5FE4F22B6D9CD6D5A87E7F1B7A198A59DBB3 which cannot be bound back to a complex object)
You could generate a form control for each property of the AssetLabel - but that would be unrealistic in your case because AssetLabel contains a property with is a collection of Conversation which in turn contains a collection of ConversationMessage so you would need nested for loops to generate an input for each property of Conversation and ConversationMessage.
But sending a whole lot of extra data to the client and then sending it all back again unchanged degrades performance, exposes unnecessary details about your data and data structure to malicious users, and malicious users could change the data).
The FinderViewModel should just contain a property for QRCode (or the ID property of AssetLabel) and in the view
#Html.HiddenFor(m => m.QRCode)
Then in the POST method, if you need the AssetLabel, get it again from the repository just as your doing it in the GET method (although its unclear why you need to AssetLabel in the POST method).
As a side note, a view model should only contain properties that are needed in the view, and not contain properties which are data models (in in your case inherit from a data model) when editing data. Refer What is ViewModel in MVC?. Based on your view, it should contain 4 properties FinderName, FinderMobile, FinderEmail and QRCode (and int? ID if you want to use it for editing existing objects).
Thanks Stephen. The QRCode is the PK on AssetLabel and the FK in Conversation so it needs to be tracked through the workflow. I was trying to keep the viewModel generic so that is can be used for other forms rather than tightly coupling it to this specific form and I was trying to pass the AssetLabel around as I have already done a significant amount of validation on it's state which I didn't want to repeat. I worked out what I need to do - If you use #Html.Hidden(model => model.AssetLabel.QRCode) then the form field name becomes AssetLabel_QRCode and is automatically mapped to the correct place in the POST viewmodel. To promote code reuse and avoid any rework later I have created this logic in a display template with the fields defined as hidden and then #Html.Partial() using the overload method that allows me to define the model extension to the form names
#Html.Partial
(
"./Templates/Assetlabel_hidden",
(GMSB.Models.AssetLabel)(Model.AssetLabel),
new ViewDataDictionary()
{
TemplateInfo = new TemplateInfo()
{
HtmlFieldPrefix = "AssetLabel"
}
}
)
But you are absolutely right, this exposes additional fields and my application structure. I think I will redraft the viewModel to only expose the necessary fields and move the AssetLabel validation to a separate private function that can be called from both the initial POST and the subsequent post. This does mean extra code in the controller as the flat vm fields need to be manually mappped to the complex object graph.
I have a two pages:
Create page that uses Data Annotations validation.
Edit page.
Both pages use different models. I have to use a specific model for the Edit page in order for the values of the selected row to display. How do I:
Get the Edit Controller to use the same validation, OR
Get the Edit page to display the current row's values if I use the same model as the Create page?
e.g.:
My Create page:
#model Test.Models.NewPerson
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Failed. Please fix the errors.")
<div class="editor-label">
#Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
<input type="submit" value="Submit" />
}
My Model:
public class NewPerson
{
[Required(ErrorMessage = "*")]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "Last name")]
public string LastName { get; set; }
}
Then my Edit page:
#model Test.Person
using (Html.BeginForm())
{
#Html.ValidationSummary(true, "Please fix the errors below.")
<div class="editor-label">
#Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
<input type="submit" value="Update" />
}
EDIT
In my controller, Edit action, I have:
var context = new MyContext();
var person = context.Person.Single(m => m.ID == id);
if (Request.IsAjaxRequest())
{
return PartialView("Edit", person);
}
return View(person);
When I put a breakpoint in that function, I am seeing results for var person. However, it returns nothing in the View. Why not?
EDIT
Here is my code for the actions:
[HttpPost]
public ActionResult Create(NewPerson model)
{
if (ModelState.IsValid)
{
string UID = Membership.GetUser().ProviderUserKey.ToString();
System.Guid myUID = System.Guid.Parse(UID);
using (var context = new MyContext())
{
Person newPerson = new Person();
newPerson.UserId = myUID;
newPerson.FirstName = model.FirstName;
newPerson.LastName = model.LastName;
context.Person.AddObject(newPerson);
context.SaveChanges();
}
}
And Edit action:
[HttpGet]
public ActionResult Edit(int id)
{
var context = new MyContext();
//recently edited: accidentally had "camper" instead of "person"
var person = context.Person.Single(m => m.ID == id);
if (Request.IsAjaxRequest())
{
return PartialView("Edit", person);
}
return View(person);
}
And my View:
#foreach (var person in Model)
{
#Html.DisplayFor(modelItem => person.LastName), #Html.DisplayFor(modelItem => person.FirstName)
#Html.ActionLink("Edit", "Edit", new { id = person.ID }, new { #class = "openDialog",
data_dialog_id = "emailDialog", data_dialog_title = "Edit Person" })
}
Both views can use the same model. That is a common practice for Create/Edit functions, and will solve problem 1, having same validation rules.
To display existing data in the input fields on the edit view, you'll need to retrieve that data in the controller and passing it to the view (ie, populate the model).
Presumably, on Edit, you will have an ID of some sort. Use that to get the proper record from the data source, and then set the FirstName and LastName values in the model. Then when you render the view (after passing in the model, of course) you'll see the existing values in the textboxes.
It's a little confusing here as to what you have and haven't done, and what does and doesn't work. However there are a few things that you should fix.
First, you should not be passing the Person object that comes from your database directly to the view. Instead, you should have your own specific Person ViewModel. This ViewModel should have your data annotations for your view on it. When you get the Person from the database, you project them into your ViewModel like this:
var camper = context.Person
.Select(m => new ViewModel.Person
{ Firstname = m.Firstname, Lastname = m.Lastname}).Single(m => m.ID == id);
This prevents your Data model's Person from being bloated by View requirements (for instance, your data model might allow nulls, but you want to set your View to be Required.)
Second, you're not using a using statement in the edit view. Something like this:
using (var camper = ..) {
...
}
Using a ViewModel helps here as well, since this allows the context to be destroyed without conflicting with the entities which are change tracked.
Third, you should probably use DisplayTemplates a little better. Rather than having the foreach statement in your view, do this:
#Html.DisplayForModel()
Then create a folder called DisplayTemplates in Views\Shared (or in the folder your view is in) and create a new .cshtml file called Person.cshtml, in that have this code:
#model Person
#Html.DisplayFor(m => m.LastName), #Html.DisplayFor(m => m.FirstName)
#Html.ActionLink("Edit", "Edit", new { id = person.ID }, new { #class = "openDialog",
data_dialog_id = "emailDialog", data_dialog_title = "Edit Person" })
I also notice some discrepancies in your namespaces. In one place you have Test.Person, in another you have Test.Models.NewPerson. Is it possible that you also have a Test.Models.Person and you're getting confused about which is which, so you end up populating the wrong one?
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 have mvc3 application in this i have used two partial views 1.controls 2.webgrid
inside controls i'm populating dropdownlists from actual database tables. using EF
On index.cshtml i have one form in which need to select values from these dropdown lists and when press insert button these values should have to go to Temp "DataTable" and also show it in webgrid...I'm newbie to MVC3 and dont know how to do this.
Controls.cshtml
#model Mapping.Models.SecurityIdentifierMappingViewModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Mapping</legend>
<div class="editor-label">
#Html.Label("Pricing SecurityID")
</div>
<div class="editor-field">
#Html.HiddenFor(model => model.MappingControls.Id)
#Html.DropDownListFor(model => model.MappingControls.PricingSecurityID,
new SelectList(Model.PricingSecurities, "Value", "Text"),
"Select SecurityID"
)
#Html.ValidationMessageFor(model => model.MappingControls.PricingSecurityID)
</div>
<div class="editor-label">
#Html.Label("CUSIP ID")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.MappingControls.CUSIP,
new SelectList(Model.CUSIPs, "Value", "Text"),
"Select CUSIP"
)
#Html.ValidationMessageFor(model => model.MappingControls.CUSIP)
</div>
<div class="editor-label">
#Html.Label("Calculation")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.MappingControls.Calculation)
#Html.ValidationMessageFor(model => model.MappingControls.Calculation)
</div>
<p>
<input id="btnsubmit" type="submit" value="Insert" />
</p>
</fieldset>
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
mydataEntities dbContext = new mydataEntities();
DataRepository objRepository = new DataRepository();
//GET
public ActionResult Index(string userAction , int uid = 0)
{
var mappingobj = new SecurityIdentifierMappingViewModel();
mappingobj.MappingWebGridList = dbContext.SecurityIdentifierMappings.ToList();
mappingobj.MappingControls = new SecurityIdentifierMapping();
mappingobj.MappingControls.PricingSecurityID = 0;
mappingobj.MappingControls.CUSIP = string.Empty;
mappingobj.PricingSecurities = objRepository.GetPricingSecurityID();
mappingobj.CUSIPs = objRepository.GetCUSIP();
return View(mappingobj);
}
//POST
[HttpPost]
public ActionResult Index(SecurityIdentifierMappingViewModel objModel)
{
if (objModel.MappingControls.Id > 0)
{
if (ModelState.IsValid)
{
dbContext.Entry(objModel.MappingControls).State = EntityState.Modified;
try
{
dbContext.SaveChanges();
//objModel = new SecurityIdentifierMappingViewModel();
//return RedirectToAction("Index", "Home");
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
throw;
}
}
}
//insert code
else
{
if (ModelState.IsValid)
{
dbContext.SecurityIdentifierMappings.Add(objModel.MappingControls);
try
{
dbContext.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
throw;
}
}
}
return RedirectToAction("Index");
}
}
public class SecurityIdentifierMappingViewModel
{
public IEnumerable<SecurityIdentifierMapping> MappingWebGridList { get; set; }
public SecurityIdentifierMapping MappingControls { get; set; }
public List<SelectListItem> PricingSecurities { get; set; }
public List<SelectListItem> CUSIPs { get; set; }
}
Currently using SecurityIdentifierMapping as a 3rd table from database in which inserting my form data ... but need to insert it into "DataTable"
You will have to create a DataTable object and assign appropriate DataColumn objects to it. After that map your SecurityIdentifierMapping properties to columns in your temporary data table. As for mapping DataTable to WebGrid, I am not going to say that it is not possible as I have never tried this thing personally, but you will have to map it back to a collection of SecurityIdentifierMapping.
But, why do you need DataTable? What possible advantages could DataTable have over IQueryable or IEnumerable? What is it that you actually want to achieve using this strategy?
UPDATE:
You are already using IEnumerable in your ViewModel class (SecurityIndentifierMappingViewModel). At the same time you are storing data in the database when POSTing to Index, and fetching again in GET version of Index.
What you are missing is to create a WebGrid object in your view. Your view could be defined like this:
#{
var columns = new List<string>();
columns.Add("Column 1");
columns.Add("Column 2");
var grid = new WebGrid(model: Model.MappingWebGridList, columnNames: columns);
}
#grid.GetHtml()
Place the above code somewhere in your Index view, and define your own columns. In addition, have a look at this article which I wrote in order to get more ideas what you can do with WebGrid http://apparch.wordpress.com/2012/01/04/webgrid-in-mvc3/.
I hope I managed to help you at least a bit.
This question is a bit different than most. My code works but I don't understand why it works.
I am trying to understand why changes made in the form get persisted after posting to the server.
Model:
public class TestUpdateModel
{
public int Id { get; set; }
public List<CarrierPrice> Prices { get; set; }
public TestUpdateModel() { } // parameterless constructor for the modelbinder
public TestUpdateModel(int id)
{
Id = id;
Prices = new List<CarrierPrice>();
using (ProjectDb db = new ProjectDb())
{
var carriers = (from c in db.Carriers
select c);
foreach (var item in carriers)
{
var thesePrices = item.Prices.Where(x => x.Parent.ParentId == Id);
if (thesePrices.Count() <= 0)
{
Prices.Add(new CarrierPrice
{
Carrier = item
});
}
else
Prices.Add(thesePrices.OrderByDescending(x => x.DateCreated).First());
}
}
}
}
Controller:
public ViewResult Test(int id = 1)
{
TestUpdateModel model = new TestUpdateModel(id);
return View(model);
}
[HttpPost]
public ViewResult Test(TestUpdateModel model)
{
model = new TestUpdateModel(model.Id);
return View(model); // when model is sent back to view, it keeps the posted changes... why?
}
View
#model Namespace.TestUpdateModel
#{ ViewBag.Title = "Test"; }
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id)
#Html.EditorFor(x => x.Prices)
<input type="submit" value="Save" />
}
EditorTemplate
#model Namespace.CarrierPrice
<tr>
<th>
#Html.HiddenFor(model => model.CarrierPriceId)
#Html.HiddenFor(model => model.DateCreated)
#Model.Carrier.Name
</th>
<td>
$#Html.TextBoxFor(model => model.Fee)
</td>
</tr>
The Source of My Confusion
1) Load the page in the browser
2) Change the value of the model.fee TextBox
3) Submit
At this point I would expect that model = new TestUpdateModel(model.Id); would create a new TestUpdateModel object and wipe out my changes so the original values re-appear when the view is returned. But what actually happens is my changes in the form are persisted to the postback.
Why does this happen?
Thanks for any help.
No. The reason is that the View Engine looks in the ModelState to fill your values before it looks at the model when it renders your view. If there are posted values, then it will find those first and use them.
If you want to override this behavior, then you need to clear the ModelState first with:
ModelState.Clear();