Remove form parameter from binding - asp.net-mvc

I have a form with some fields, and depending of the data i dont want to save all to database.
lets say, i have this controler
public ActionResult Edit([Bind(Include = "id,Costumer, City ,Obs")] Clients clients)
{
if (ModelState.IsValid)
db.Entry(clients).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(clients);
}
but i somecases i dont want to save the City.
How can i remove the City from being save to database ?
I've tryied with
ModelState.Remove("City");
but it keeps saving to database

If City is a navigation property, then something like:
db.Entry(clients.City).State = EntityState.Unchanged;
if City is a string then
db.Entry(clients).Property("City").IsModified = false;

Related

Why 3 ways to do MVC 5 Model Binding?

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".

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

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.

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.

Return action does not work correctly

I have a simple create action that save a product to DB. after saving the product I have used return View(new Product()); to reset the form fields but the form show the old data(the data before submit the form). Also I use return View(new Product(name="test")); but it does not work too.
what is the problem? the product is saved to DB correctly (it means ModelState.IsValid is true). I don Not want to use RedirectToAction.
[HttpPost]
public ActionResult New(Product product)
{
if (ModelState.IsValid)
{
product.SubmitDate = DateTime.UtcNow;
productRepository.Add(product);
productRepository.Save();
//ViewBag.Message = "product is saved";
return View(new Product());
}
return View(product);
}
I think the recommended practice is to use RedirectToAction() but if you want to try it your way, you could try
ModelState.Clear();
return View(new Product());
If you intend to modify a property which is already in the model state you will need to remove it or the HTML helpers that are bound to this value would always use the value in the model state and not the one that you modified:
ModelState.Remove("SubmitDate");
product.SubmitDate = DateTime.UtcNow;
return View(product);
And if you want to clear all properties it would be better to redirect or clear the entire model state collection: ModelState.Clear();

Resources