asp.mvc 4 EF ActionResult Edit with not all fields in view - asp.net-mvc

The standard generated code bock for responding to the Edit save form
[HttpPost]
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
works when all fields are present in the edit view.
In my model I have a password field that (for obvious reasons) I don't want to pass as an invisible form field.
As a result password is null (which is to be expected).
How should I code to handle this scenario?
get the password value, should I fetch the value from the database?
if I use: User u = db.User.Find(user.ID); EF has issues with "an object with the same key already exists in the ObjectStateManager"
how do I tackle the ModelState.IsValid as it is false
I have found answers for previous mvc versions, but was wondering what is the most elegant / efficient way of achieving this?
#freeride, surly I don't have to test if user.Password is null, I expect it to be null and if it isn't then it was injected by a malicious user. The entire excersie was to avoid user manipulation of the password.
Removing the password field (ModelState.Remove("Password");) does solve the ModelState validation issue.
Now remains the question, how do I restore the password value? Following works:
[HttpPost]
public ActionResult Edit(user user)
{
user v = db.Users.Find(user.ID);
ModelState.Remove("Pass");
user.Password = v.Password; // assign from db
if (ModelState.IsValid)
{
//db.Entry(user).State = EntityState.Modified; // this won't work as the context changed
db.Entry(v).CurrentValues.SetValues(user); // we need to use this now
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
I wonder if I'm obliged to do an extra db trip to fetch the value? I had to change the code to fix the EF context change, it works, but is the code right?

Before
if (ModelState.IsValid)
add
if (string.IsNullOrEmpty(user.Password))
{
ModelState.Remove("Password");
}
I wonder if I'm obliged to do an extra db trip to fetch the value? I
had to change the code to fix the EF context change, it works, but is
the code right?
Do it in a different way. Don't use an entity object as your model.
Create a model which contains only data you need to update,for example:
public class UserModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
}
and now:
[HttpPost]
public ActionResult Edit(UserModel userModel)
{
if (ModelState.IsValid)
{
User user = db.Users.Find(userModel.Id);
user.FirstName = userModel.FirstName ;
user.Surname = userModel.Surname;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userModel);
}
I hope it helps.

Related

Submitting form data to multiple tables. NullReferenceException

Hey could someone please help me submit this form? Here is my ViewModel that I made. This is my third day trying to pick up MVC so I'm still new to this.
public class EmployeeAllData
{
public Employees Employees { get; set; }
public PermissionModel PermissionModel { get; set; }
}
Here is my controller for the form submit. I'm starting with the permission table and I'm not having any luck. It keeps giving me this error: NullReferenceException was unhandled by user code. I tried hard coding values and it updated the permissions table just fine. I can't find out why I'm not getting a value back from Employees.
[HttpPost]
public ActionResult Create(EmployeeAllData viewModel)
{
var permission = new PermissionModel
{
EmployeesId = Convert.ToByte(viewModel.Employees.Id),
TimeStamp = DateTime.Now,
PermissionVal = viewModel.Employees.Permissions
};
_context.PermissionModels.Add(permission);
_context.SaveChanges();
return RedirectToAction("EmployeeList", "Employee");
}
Any ideas?
UPDATE
I think my problem is with my ViewModel. The code below runs fine and creates a new employee in the database.
public ActionResult Create(Employees employees)
{
_context.Employeeses.Add(employees);
_context.SaveChanges();
return RedirectToAction("EmployeeList", "Employee");
}
I did not need to use a viewModel. Here is my final code that now works.
[HttpPost]
public ActionResult Create(Employees employees)
{
_context.Employeeses.Add(employees);
_context.SaveChanges();
var permission = new PermissionModel()
{
EmployeesId = Convert.ToByte(employees.Id),
TimeStamp = DateTime.Now,
PermissionVal = employees.Permissions
};
_context.PermissionModels.Add(permission);
_context.SaveChanges();
return RedirectToAction("EmployeeList", "Employee");
}

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.

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");
}

Model not populated on HTTPost

I have a create action that doesn't send the CreatedOn and CreatedBy back to the HttpPost create action.
These are not user definable properties, and ideally i don't want them displayed on the form at all. So how do i get these properties into the model, without having them on the form itself? Should they be hidden fields on the form?
The Controller
public virtual ActionResult Create()
{
var meeting = new Meeting
{
CreatedOn = DateTime.Now,
CreatedBy = User.Identity.Name,
StartDate = DateTime.Now.AddMinutes(5),
EndDate = DateTime.Now.AddHours(3)
};
ViewBag.Title = "Create Meeting";
return View(meeting);
}
[HttpPost]
public virtual ActionResult Create(Meeting meeting)
{
if (ModelState.IsValid)
{
_meetingRepository.InsertOrUpdate(meeting);
_meetingRepository.Save();
return RedirectToAction(MVC.Meetings.Details(meeting.MeetingId));
} else {
return View();
}
}
Should they be hidden fields on the form?
Yes, that's definitely one good way of passing them. Note that this is not secure because the user can fake a POST request and modify them but that could be OK in your scenario.
So if you need security another way is to re-fetch them from the data store as the user cannot modify them in this form so they haven't changed.

MVC - Default Value in Field

I have the following code in my controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")] BackupSet AccountToCreate)
{
if (!ModelState.IsValid)
return View();
_DBE.AddToBackupSet(AccountToCreate);
_DBE.SaveChanges();
return RedirectToAction("Index");
}
I need to have the value of User.Identity.Name set to be the value of one of the fields in the create view when I post it to the database.
I am sure its very simple but really don't know how.
Thanks,
Steve.
Why do you need to store the username in the view? You will surely be initiating the DB transaction from within a controller so if it's the username for the user that is currently logged in use the MembershipProvider as per the last suggestion:
HttpContext.Current.User.Identity.Name
If not perhaps you should consider creating a container/wrapper class that clearly represents your View model - some might consider this overkill for one extra property but I hate "magic strings" in code.
public class MyView
{
public string UserName { get; set; }
public MyObject MyMainObject { get; set;}
public MyView(string username, MyObject myMainObject)
{
this.Username = username;
this.MyMainObject = myMainObject;
}
}
then set your view model type as:
System.Web.Mvc.ViewPage<MyNamespace.MyView>
this then allows you to have strongly typed properties for everything in your view e.g.
<%=Model.Username %>
<%=Model.MyMainObject.Title %>
and in your controller you can parameterize your Action as
public ActionResult(MyMainObject myMainObject, string username)
{
//Do something here
//if not correct
return View(new MyView(username, myMainObject));
}
If instead you wanted to go down this path:
ViewData["Name"] = User.Identity.Name;
or
ViewData.Add("Name", User.Identity.Name);
Consider creating Enums to once again avoid using string literals e.g.
public enum UserEnum
{
Username,
Password
}
then use:
ViewData.Add(UserEnum.Username.ToString(), User.Identity.Name);
one of the fields in view?
how about simply setting
ViewData["Name"] = User.Identity.Name
and then in View use it wherever you want.
Short Answer:
HttpContext.Current.User.Identity.Name
Long Answer:
You should probably make a membership service to provide that value. The default MVC2 project will provide IMembershipService interface which you can expand to provide property: CurrentUserName (or whatever you like)
public string CurrentUserName
{
get
{
var context = HttpContext.Current;
if (null != context)
return context.User.Identity.Name;
var user = Thread.CurrentPrincipal;
return (null == user)
? string.Empty
: user.Identity.Name;
}
}

Resources