Why 3 ways to do MVC 5 Model Binding? - asp.net-mvc

I'm reading Professional ASP.Net MVC 5 and the section on Model Binding shows 3 ways to do the same thing. They are listed below. Can anyone explain the pros and cons of each method?
The first example uses if ModelState.IsValid
the second example uses if TryUpdateModel
The third uses both.
What am I missing here? All seem to work. Why 3 ways to write it?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit (Album album)
{
if (ModelState.IsValid)
{ db.Entry( album). State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction(" Index");
}
return View( album);
}
View( album);
}
[HttpPost]
public ActionResult Edit()
{
var album = new Album();
if (TryUpdateModel( album))
{ db.Entry( album). State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction(" Index");
}
else
{
return View( album);
}
}
[HttpPost]
public ActionResult Edit()
{
var album = new Album();
TryUpdateModel( album);
if (ModelState.IsValid)
{
db.Entry( album). State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction(" Index");
}
else
{
return View( album);
}
}

The first is very simple and supports the most common use where simply newing up the model and mapping the data to it is fine. The instance creation and mapping is handled automatically and "just works".
The third allows you map the incoming data to an existing object instance. If for some reason you already have an object instance you want to map the data too (it probably already has extra data in you want to use and that data doesn't exist in a new instance MVC would automatically create) then this is how you would do it.
The second is the same as the third, but allows you to differentiate between "The model failed to update" and "the model updated, but is invalid".

Related

How do I save Entity with WCF

What is the best practice for saving an entity in wcf. I am calling my service through asp.net mvc site.
I have declared my context in the .svc file, as I would with normal winforms development.
public ScoolEntities database = new ScoolEntities();
Then I am using the following to get the data by id.
public student GetStudentsById(int id)
{
var q = (from mystudent in database.students where mystudent.id == id select mystudent);
return q.ToList()[0];
}
Then Finally I have a public save method
public bool savechanges()
{
database.SaveChanges();
return true;
}
Then in my controller I have
public ActionResult Edit(int id=0)
{
return View(obj.GetStudentsById(id));
}
[HttpPost]
public ActionResult Edit(MvcApplication1.ServiceReference1.student student)
{
if (ModelState.IsValid)
obj.savechanges();
return RedirectToAction("Index");
}
return View();
}
But it does not appear to save the changes and also what do I need to place in the return view I would have thought I call the GetStudents again but it does not appear to work?.
You need to add the Entity to the Context and need to call SaveChanges method.
database.Students.Add(student);
database.SaveChanges();

Survey Controller POST method problems ASP.NET MVC

I'm attempting to create a single Controller class to handle all foreseeable surveys that I'll end up creating in the future. Currently I have a 'Surveys' table with fields: Id, SurveyName, Active. On the 'master' Surveys' Index page I list out every SurveyName found in that table. Each SurveyName is clickable, and when clicked on, the page sends the SurveyName as a string to the receiving controller action. Said controller action looks like this:
//
//GET: /Surveys/TakeSurvey/
public ActionResult TakeSurvey(string surveyName)
{
Assembly thisAssembly = Assembly.GetExecutingAssembly();
Type typeToCreate = thisAssembly.GetTypes().Where(t => t.Name == surveyName).First();
object newSurvey = Activator.CreateInstance(typeToCreate);
ViewBag.surveyName = surveyName;
return View(surveyName, newSurvey);
}
Using reflection I am able to create a new instance of the type (Model) designated by the passed-in string 'surveyName' and am able to pass that Model off to a view with the same name.
EXAMPLE
Someone clicks on "SummerPicnic," the string "SummerPicnic" is passed to the controller. The controller, using reflection, creates a new instance of the SummerPicnic class and passes it to a view with the same name. A person is then able to fill out a form for their summer picnic plans.
This works all fine and dandy. The part that I'm stuck at is trying to save the form passed back by the POST method into the correct corresponding DB table. Since I don't know ahead of time what sort of Model the controller will be getting back, I not only don't know how to tell it what sort of Model to save, but where to save it to, either, since I can't do something ridiculous like:
//
//POST: Surveys/TakeSurvey
[HttpPost]
public ActionResult TakeSurvey(Model survey)
{
if (ModelState.IsValid)
{
_db. + typeof(survey) + .Add(survey);
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View();
}
Is there a way to do this, or should I go about this from a whole different angle? My ultimate goal is to have a single Controller orchestrating every simple-survey, so I don't have to create a separate controller for every single survey I end up making down the road.
An alternative solution I can think of is to have a separate method for every survey, and to have which method to call defined inside of every survey's view. For example, if I had a SummerPicnic survey, the submit button would call an ActionMethod called 'SummerPicnic':
#Ajax.ActionLink("Create", "SummerPicnic", "Surveys", new AjaxOptions { HttpMethod = "POST" })
A survey for PartyAttendance would call an ActionMethod 'PartyAttendance,' etc. I'd rather not have to do that, though...
UPDATE 1
When I call:
_db.Articles.Add(article);
_db.SaveChanges();
This is what _db is:
private IntranetDb _db = new IntranetDb();
Which is...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace Intranet.Models
{
public class IntranetDb : DbContext
{
public DbSet<Article> Articles { get; set; }
public DbSet<ScrollingNews> ScrollingNews { get; set; }
public DbSet<Survey> Surveys { get; set; }
public DbSet<Surveys.test> tests { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
You can try something like this,
UPDATE:
The built-in UpdateModel will work with generic model see this post, so we got little more work.
[HttpPost]
public ActionResult TakeSurvey(FormCollection form, surveyName)
{
var surveyType = Type.GetType(surveyName);
var surveyObj = Activator.CreateInstance(surveyType);
var binder = Binders.GetBinder(surveyType);
var bindingContext = new ModelBindingContext()
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => surveyObj, surveyType),
ModelState = ModelState,
ValueProvider = form
};
binder.BindModel(ControllerContext, bindingContext);
if (ModelState.IsValid)
{
// if "db" derives from ObjectContext then..
db.AddObject(surveyType, surveyObj);
db.SaveChanges();
// if "db" derives from DbContext then..
var objCtx = ((IObjectContextAdapter)db).ObjectContext;
objCtx.AddObject(surveyType, surveyObj);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View();
}
Check this two know the diff between DbContext and ObjectContext
I ended up with a slightly modified version of Mark's code:
[HttpPost]
public ActionResult TakeSurvey(string surveyName, FormCollection form)
{
//var surveyType = Type.GetType(surveyName);
//var surveyObj = Activator.CreateInstance(surveyType);
// Get survey type and create new instance of it
var thisAssembly = Assembly.GetExecutingAssembly();
var surveyType = thisAssembly.GetTypes().Where(t => t.Name == surveyName).First();
var newSurvey = Activator.CreateInstance(surveyType);
var binder = Binders.GetBinder(surveyType);
var bindingContext = new ModelBindingContext()
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => newSurvey, surveyType),
ModelState = ModelState,
ValueProvider = form
};
binder.BindModel(ControllerContext, bindingContext);
if (ModelState.IsValid)
{
var objCtx = ((IObjectContextAdapter)_db).ObjectContext;
objCtx.AddObject(surveyName, newSurvey);
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View();
}
I was running into surveyType being 'null' when it was set to Type.GetType(surveyName); so I went ahead and retrieved the Type via Reflection.
The only trouble I'm running into now is here:
if (ModelState.IsValid)
{
var objCtx = ((IObjectContextAdapter)_db).ObjectContext;
objCtx.AddObject(surveyName, newSurvey);
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
When it tries to AddObject I'm getting the exception "The EntitySet name 'IntranetDb.test' could not be found." I just need to figure out to strip off the prefix 'IntranetDb.' and hopefully I'll be in business.
UPDATE
One thing I completely overlooked was passing the Model to the controller from the View...oh bother. I currently have an ActionLink replacing the normal 'Submit' button, as I wasn't sure how else to pass to the controller the string it needs to create the correct instance of Survey model:
<p>
#Ajax.ActionLink("Create", "TakeSurvey", "Surveys", new { surveyName = ViewBag.surveyName }, new AjaxOptions { HttpMethod = "POST" })
#*<input type="submit" value="Create" />*#
</p>
So once I figure out how to turn 'IntranetDb.test' to just 'test' I'll tackle how to make the Survey fields not all 'null' on submission.
UPDATE 2
I changed my submission method from using an Ajax ActionLink to a normal submit button. This fixed null values being set for my Model values after I realized that Mark's bindingContext was doing the binding for me (injecting form values onto the Model values). So now my View submits with a simple:
<input type="submit" value="Submit" />
Back to figuring out how to truncate 'IntranetDb.test' to just 'test'...
Got It
The problem lies in my IntranetDb class:
public class IntranetDb : DbContext
{
public DbSet<Article> Articles { get; set; }
public DbSet<ScrollingNews> ScrollingNews { get; set; }
public DbSet<SurveyMaster> SurveyMaster { get; set; }
public DbSet<Surveys.test> tests { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
objCtx.AddObject(surveyName, newSurveyEntry); was looking for an entry (an "EntitySet") in the IntranetDb class called "test." The problem lies in the fact that I don't have an EntitySet by the name of "test" but rather by the name of "tests" with an 's' for pluralization. Turns out I don't need to truncate anything at all, I just need to point to the right object :P Once I get that straight I should be in business! Thank you Mark and Abhijit for your assistance! ^_^
FINISHED
//
//POST: Surveys/TakeSurvey
[HttpPost]
public ActionResult TakeSurvey(string surveyName, FormCollection form)
{
//var surveyType = Type.GetType(surveyName);
//var surveyObj = Activator.CreateInstance(surveyType);
// Create Survey Type using Reflection
var thisAssembly = Assembly.GetExecutingAssembly();
var surveyType = thisAssembly.GetTypes().Where(t => t.Name == surveyName).First();
var newSurveyEntry = Activator.CreateInstance(surveyType);
// Set up binder
var binder = Binders.GetBinder(surveyType);
var bindingContext = new ModelBindingContext()
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => newSurveyEntry, surveyType),
ModelState = ModelState,
ValueProvider = form // Get values from form
};
var objCtx = ((IObjectContextAdapter)_db).ObjectContext;
// Retrieve EntitySet name for Survey type
var container = objCtx.MetadataWorkspace.GetEntityContainer(objCtx.DefaultContainerName, DataSpace.CSpace);
string setName = (from meta in container.BaseEntitySets
where meta.ElementType.Name == surveyName
select meta.Name).First();
binder.BindModel(ControllerContext, bindingContext); // bind form values to survey object
if (ModelState.IsValid)
{
objCtx.AddObject(setName, newSurveyEntry); // Add survey entry to appropriate EntitySet
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View();
}
It's kind of bloated but it works for now. This post helped me get the EntitySet from the Survey object itself so I didn't need to worry about establishing some sort of EntitySet naming convention.
The main problem I see is to bind to the model to the TakeSurvey POST method. If you want different types of survey models should be handled by this method and MVC should bind to this model before calling the action, I believe you can have a wrapper model class over all such generic model, say SurveyModel and use custom model binder to bind to these models.
public class SurveyModel
{
public string GetSurveyModelType();
public SummerPicnicSurvey SummerPicnicSurvey { get; set; }
public PartyAttendanceSurvey PartyAttendanceSurvey { get; set; }
}
Then write a custom mobel binder to bind this model. From the request form fields we can see what type of survey model is posted and then accordingly fetch all the fields and initialize the SurveyModel class. If SummerPicnicSurvey is posted then class SurveyModel will be set with this class and PartyAttendanceSurvey will be null. Example custom model binder.
From the controller action TakeSurvey POST method, You can update db like this:
[HttpPost]
public ActionResult TakeSurvey(SurveyModel survey)
{
if (ModelState.IsValid)
{
if(survey.GetSurveyModelType() == "SummerPicnicSurvey")
_db.UpdateSummerPicnicSurvey(survey.SummerPicnicSurvey);
else if (survey.GetSurveyModelType() == "PartyAttendanceSurvey")
_db.UpdateSummerPicnicSurvey(survey.PartyAttendanceSurvey);
_db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View();
}
Instead of SurveyModel encapsulating the other surveys you can have inheritance and use .net as to typecast with a check and use the Model.
Having said this, I think there is no harm in using different methods for each model. This will enable you to unit test the code well. Too many if else is not healthy to maintain. Or you can transfer the generic model SurveyModel to the repository or data access layer and let it handle that in a polymorphic way. I would prefer more small functions and keep the code clean.
Edit: The inheritance way:
public class SurveyModel
{
public virtual bool Save();
}
public partial class SummerPicnicSurvey : SurveyModel
{
public bool Save(SummerPicnicSurvey survey)
{
using(var _dbContext = new MyContext())
{
_dbContex.SummerPicnicSurveys.Add(survey);
_dbContex.SaveChanges();
}
}
}
[HttpPost]
public ActionResult TakeSurvey(SurveyModel survey)
{
if (ModelState.IsValid)
{
survey.Save();
return RedirectToAction("Index", "Home");
}
return View();
}
Any new Survey model type you add has to implement the SaveChanges or Save method, Which would call the proper dbcontext method. The controller action would just call Save on the generic `SurveyModel' reference passed to it. Thus the action will be closed for modification but open for modification. The open-close design principle.

Update single property of an entity using Entity Framework and ASP.NET MVC

I'm trying to use Entity Framework in an ASP.NET MVC web application.
Let's say I have an Entity "people", with some anagraphical details.
My web application has a view where, using Ajax, I can change my details one by one.
For example, I can change only the "name" of my entity, using an Ajax post.
What's the best practice to implement a method in my controller to perform this update on my "people" entity?
I would like to create a general "update" method, not a specific method for each single property.
Thanks for helping me
public ActionResult Update(int id, string propertyName, object propertyValue)
{
using(var ctx = new Db())
{
var person = ctx.People.First(n => n.Id == id);
Type t = person.GetType();
PropertyInfo prop = t.GetProperty(propertyName);
prop.SetValue(person, propertyValue, null);
ctx.SaveChanges();
}
return Json(new { Success = true });
}
Why would you want to do that? Just pass the whole Entity and update it, it's in your view model anyways.
[HttpPost]
public ActionResult Edit(People people)
{
if (ModelState.IsValid)
{
db.Entry(people).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(people);
}

linq to sql question , why my change is not saved?

this is my first mvc 3 project, i am using linq to sql.
public ActionResult Edit(int ID)
{
try
{
Tutorial tut = reposi.Tutorials.Single(d => d.TutorialID == ID);
return View(tut);
}
catch
{
return RedirectToAction("List");
}
}
[HttpPost]
public ActionResult Edit(Tutorial tut)
{
if (ModelState.IsValid)
{
//tut.TutorialID = ID;
tut.EditDate = DateTime.Now;
tutContext.SubmitChanges();
return RedirectToAction("List");
}
else
{
return View(tut);
}
}
after I click on the "Edit" button, It takes me back to list page, and changes are not saved. still old values.
You need to first get the Tutorial from your database, then make the changes, then SubmitChanges().
[HttpPost]
public ActionResult Edit(Tutorial tut)
{
if (ModelState.IsValid)
{
Tutorial t = tutContext.get(tut.Id);
//tut.TutorialID = ID;
t.EditDate = DateTime.Now;
tutContext.SubmitChanges();
return RedirectToAction("List");
}
else
{
return View(tut);
}
}
Note, your tutContext.get(tut.Id); may be different depending on your implementation.
tut.EditDate = DateTime.Now;
tutContext.SubmitChanges();
return RedirectToAction("List");
Your tutorial object is not managed by db context yet. so the context didn't save the object change when you change the tut object and invoke tutContext.SubmitChanges().
First thing first, you must lookup the tutorial object from the context.
Tutorial tut = ctx.Tutorials.Single(d => d.TutorialID == ID);
after you get the tuts object form the tuts context, that tuts object is managed by the db context. then you can modify the tut object and submit the changes.
Tutorial tut = ctx.Tutorials.Single(d => d.TutorialID == tut.ID);
tut.EditDate = DateTime.Now;
ctx.SubmitChanges();
You need this in the [HttpPost]
When you debug, are you reaching the Post action in the controller? Make sure your form action is set to POST instead of GET.

Optimal Way to Load Objects in an HttpPost Action Method in ASP.NET MVC

I'm using ASP.NET MVC 3 and Entity Framework 4.1.
I was wondering what is the preferred method of updating a object when not all of the properties are provided in the HTTP Post.
For example, an Order object may have the properties of Items, CreateDate and UpdateDate. In an edit form only the Items property will be entered and posted to the Edit ActionMethod. So the below basic code will fail as the CreateDate and UpdateDate properties are not included with the order.
[HttpPost]
public ActionResult Edit(Order order)
{
{
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(order);
}
What is the best way to handle this situation? For simple objects such as this order I suppose the CreateDate and UpdateDate can be kept in hidden fields, however, for more complex objects (such as those with several one-to-many relationships) should the object id be used to retrieve the full object and then overwrite some of its properties with the values posted back in the form...
One option is to create view models
public class OrderEditModel
{
//properties used in the view
}
[HttpPost]
public ActionResult Edit(OrderEditModel orderEditModel)
{
// map OrderEditModel to Order
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
You can use AutoMapper to map them
Other option is to retrieve the object from database and update it
[HttpPost]
public ActionResult Edit(string id)
{
var order = db.Orders.FindByKey(id);
UpdateModel(order);
db.SaveChanges();
return RedirectToAction("Index");
}
In the scenario, where the createdate and modifydate are in hidden inputs on the Form that posted (named createDate and modDate), then you can retrieve them from the request form collection as follows, even though they are not on the Order object.
[HttpPost]
public ActionResult Edit(Order order)
{
var createdOn = this.Request.Form["createDate"];
var editedOn = this.Request.Form["modDate"];
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}

Resources