Model not populated on HTTPost - asp.net-mvc

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.

Related

Remove form parameter from binding

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;

The model on a view is null when using RedirectToAction

I am using RedirectToAction to load a new page after login and pass in the database model with it.
RedirectToAction("AdministrationPortal", "Manage", person);
person.user model is a User class created by the entity framework. The model of person is
class Person {
public User user { get; set; };
public string roleType { get; set; };
}
I node the person object did hold the data at the time where RedirectToAction got called.
Don't know why when I user it on a portal page #Model.Person.user is null.
#model namespace.Model.Person
You cannot pass complex objects when redirecting using RedirectToAction.
It is used for passing the routeValues not the Model.
To maintain state temporarily for a redirect result, you need to store your data in TempData.
You can refer this for more info: passing model and parameter with RedirectToAction
TempData["_person"] = person;
return RedirectToAction("AdministrationPortal", "Manage");
Then
public ActionResult AdministrationPortal()
{
Person p_model = (Person)TempData["_person"];
return View(p_model);
}
When I need to send a model in RedirectToAction, I simply pass id like (lets say you person has id):
return RedirectToAction("AdministrationPortal", "Manage", new { #id=person.Id} );
Then at controller:
public ActionResult AdministrationPortal(long id)
{
//Get Person from DB
var model=GetPersonById(id);
return View(model);
}
I personally don't like using TempData but if you like to use it then:
TempData["Person"] =person;
return RedirectToAction("AdministrationPortal", "Manage");

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

Mandatory field while creating new database record in asp.net mvc

I'm new to ASP.NEt MVC. I've been trying to create a new database record.
public ActionResult Create()
{
var model = new Maping();
return View(model);
}
//
// POST: /Customerservice/Create
[HttpPost]
public ActionResult Create([Bind(Exclude="CustomerServiceMappingID")] Maping serviceToCreate)
{
if (!ModelState.IsValid)
return View();
var dc = new ServicesDataContext();
String s = serviceToCreate.ServiceID.ToString();
if (String.IsNullOrEmpty(s))
ModelState.AddModelError("ServiceID", "ServiceID is required!");
dc.Mapings.InsertOnSubmit(serviceToCreate);
dc.SubmitChanges();
return RedirectToAction("Index","Home");
}
So, what I need to do is I need ServiceID to become mandatory... I tried this with not much use. So, can u please help me out?
Also I need to send the customerID which is another column of the table back to Index method.
If ServiceId is an integer it should automatically be required. Otherwise you can put this attribute on ServiceId in your model class.
[Required]
public string ServiceId {get;set;} //assuming you are using a string
Can you post your model?
Two things ...
1)
You need to add the Is Null = false to your database model, so that when the DataContext tries to save the new record away, then it will either create a new ID if those attributes are set or you need to supply one.
2)
Add an Attribute to your Maping model that tells MVC about the error you are throwing in the Create Action.
[Required]
public int ServiceID // <- replace with the correct type.
if your Index Action is like this ...
public ActionResult Index(int customerID), then you can send it with the RedirectToAction.
new { customerId = /* insert ID here */ }
that I believe is the third parameter in that method call.

Resources