asp.net MVC 3 Error: "Object reference not set to an instance of an object" - asp.net-mvc

i've a AccountController like this
public class AccountController : Controller
{
[Authorize]
public ActionResult MyProfile(string userEmail)
{
UserManager um = new UserManager();
UserProfile user = new UserProfile();
user = um.GetUserDetail(userEmail);
return View(user);
}
}
i've UserManager.cs Like this
public class UserManager
{
private ToLetDBEntities TLE = new ToLetDBEntities();
public UserProfile GetUserDetail(string uemail)
{
var userDetails = TLE.users.FirstOrDefault(x => x.email_add == uemail);
UserProfile up = new UserProfile();
up.cellno = userDetails.cellno.Trim();
up.email_add = userDetails.email_add.Trim();
up.name = userDetails.name.Trim();
up.password = userDetails.password.Trim();
return up;
}
}
When i'm debugging it gives error like
Object reference not set to an instance of an object
Null Reference Exception was Unhandled by User
At the line
up.cellno=userDetails.cellno.Trim();
Of the GetUserDetails function.

That error suggests that you don't have a userDetails instance, so you can't get the cellno property.
Are you sure that TLE.users.FirstOrDefault(x => x.email_add == uemail) is returning something? If you put a breakpoint on the line that gives you the error, then you can check what the value of userDetails is - it's probably null.

Most likely this query isn't returning anything:
TLE.users.FirstOrDefault(x => x.email_add == uemail);
The FirstOrDefault method won't give any kind of indication if no record is returned. The OrDefault part specifies this behavior. For any given return type, it will return the "default" for that type if no record is found.
For reference types (which yours is), the default is null. So this call would result in exactly that exception:
userDetails.cellno.Trim();
Since userDetails is null then it can't access a cellno property, hence the exception.
It's also possible in your case that userDetails isn't null but that the cellno property on it is. It's less likely, but possible. Looking at the runtime value while debugging would tell you if that's the case.
If userDetails is null, check your query conditions. Maybe the users collection has nothing in it? Maybe there are no records which match your x.email_add == uemail condition? (This is likely.)
If cellno is null then you'll want to check how that object is built, what the data in the database looks like, etc. Either way, you're not getting back the data you expect. The issue is in the data you're accessing.

Related

breezejs cancel saveChanges due to validation failure in BeforeSaveEntity

I created my own ContextProvider, sub classed from EFContextProvider. In BeforeSaveEntity I am running some business logic to validate the transaction. I need the updates to be "all or nothing", so if the 3rd entity in the collection fails the validation, the entire batch should be discarded, even though Ive already returned "true" for the first 2 entities.
I have a class level property thats getting set when any entity fails. In the final check in BeforeSaveEntities I can get the value of the flag.
I think this is where I can abort the update, but not sure how. Do I clear the map? Or throw an error?
Also, I will need to re-query the DB for my validation routines. I've read some posts that talk about creating a 2nd instance of the context to do the querying for the current values. Is there some docs on doing this, or gotchas I need to be aware of?
thanks
In your BeforeSaveEntities call you can throw an EntityErrorsException: Here is an example where we throw an exception if there is attempt to save any "Order" objects within a save bundle:
[HttpPost]
public SaveResult SaveWithEntityErrorsException(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = ThrowEntityErrorsException;
return ContextProvider.SaveChanges(saveBundle);
}
private Dictionary<Type, List<EntityInfo>> ThrowEntityErrorsException(Dictionary<Type, List<EntityInfo>> saveMap) {
List<EntityInfo> orderInfos;
if (saveMap.TryGetValue(typeof(Order), out orderInfos)) {
var errors = orderInfos.Select(oi => {
return new EntityError() {
EntityTypeName = typeof(Order).FullName,
ErrorMessage = "Cannot save orders with this save method",
ErrorName = "WrongMethod",
KeyValues = new object[] { ((Order) oi.Entity).OrderID },
PropertyName = "OrderID"
};
return new EFEntityError(oi, "WrongMethod", "Cannot save orders with this save method", "OrderID");
});
var ex = new EntityErrorsException("test of custom exception message", errors);
// if you want to see a different error status code use this.
// ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403).
throw ex;
}
return saveMap;
}
And you should use BeforeSaveEntities exclusively instead of BeforeSaveEntity as your save logic becomes more complicated.
I had a requirement to perform server side calculations on entities that had been changed on the client - without saving - and get the results back to the client. The solution based on Breeze named saves that I came up with could be useful in this situation too.
I added the following method to the base class for my Breeze controllers.
protected SaveResult OverrideSaveChanges(JObject saveBundle, Action<List<object>> action, bool shouldSave = false)
{
var saveChangesDelegate = new SaveChangesOverride(action, shouldSave);
return saveChangesDelegate.Execute(saveBundle, ContextProvider);
This allows concrete controllers to implement named saves very simply. The saveBundle plus an Action<List<object>> are passed into the OverrideSaveChanges method. The action can make whatever modifications to the entities that are required and those changes will be propagated back to the client. The objects in the list are the entities that the client recognized as having changes and sent down to the server for the named save. Optionally, you could pass a shouldSave argument with a value of true to have the entities saved - the default is false.
OverrideChanges delegates to SaveChangesOverride for most of the heavy lifting.
public class SaveChangesOverride
{
public SaveChangesOverride(Action<List<object>> action, bool shouldSave = false)
{
Action = action;
ShouldSave = shouldSave;
}
private readonly Action<List<object>> Action;
private readonly bool ShouldSave;
public List<object> Entities;
public SaveResult Execute(JObject saveBundle, ContextProvider contextProvider)
{
contextProvider.BeforeSaveEntitiesDelegate = OnBeforeSaveEntities;
contextProvider.SaveChanges(saveBundle);
return new SaveResult
{
Entities = Entities,
KeyMappings = new List<KeyMapping>()
};
}
private Dictionary<Type, List<EntityInfo>> OnBeforeSaveEntities(Dictionary<Type, List<EntityInfo>> arg)
{
Entities = arg.SelectMany(x => x.Value).Select(x => x.Entity).ToList();
Action(Entities);
if (!ShouldSave)
{
return new Dictionary<Type, List<EntityInfo>>();
}
return arg;
}
}
Although we have access to all of the changed entities in the saveBundle actually performing the modifications in OnBeforeSaveChanges allows us to work with entities rather than a JObject.
Also, contextProvider.SaveChanges must be called regardless of whether we wish to have the entities saved. This is what triggers OnBeforeSaveEntities to be called. To ensure that the entities are not saved despite calling SaveChanges (if that is what is desired), rather than returning arg from OnBeforeSaveEntities, an empty dictionary is returned.
To ensure that the changes make it back to the client, a reference to the entities is saved in OnBeforeSaveEntities. This is used in Execute to prepare a SaveResult that is populated with the modified entities.

ASP MVC 3 Base controller for entity context access

I've implemented a base controller for my MVC 3 project to allow a common way of accessing a user entity from my db context :
public abstract class MyBaseController : Controller
{
protected DBEntitiesContainer db;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
this.db = new DBEntitiesContainer();
}
public UserDetails GetActiveUserDetails()
{
UserDetails userDetails = GetObjects.GetActiveUserDetails(this.db);
return userDetails;
}
}
This works great and all my controllers have access to this.db.MyEntity and can retrieve a UserDetails object by calling this.GetActiveUserDetails()
However, the problem arises when I try to perform an update on the entity thus :
public class UpdateController : MyBaseController
{
public ActionResult Index()
{
UserDetails userDetails = this.GetActiveUserDetails();
userDetails.LastOnline = DateTime.Now;
UpdateModel(userDetails);
this.db.SaveChanges();
}
}
Any ideas why the UserDetails object is easily retrieved, but when I check my database after calling SaveChanges(), nothing has been updated ? I'm presuming I'm accessing my context in two different ways, but I can't see how I am...!
Edit: Here's the GetObjects.GetActiveUserDetails() method
public static UserDetails GetActiveUserDetails(DBEntitiesContainer db)
{
MembershipUser membershipUser = Membership.GetUser();
UserDetails userDetails;
try
{
if (membershipUser != null)
{
userDetails = (from u in db.UserDetails
where (u.UserId == (System.Guid)membershipUser.ProviderUserKey)
select u).First();
}
else
{
return GetGuestAccount();
}
}
catch
{
return GetGuestAccount();
}
return userDetails;
}
Not the cleanest method I know...
UpdateModel is helper method for Controller base class. it supports updating the properties of an object we pass it using the incoming form parameters during HttpPost action method.
It uses relfection to find out the property names of the object (Model object what we passed) and then automatically converts the assigns values to them based on the input values submitted by the form ( client form).
In your case you when u use update model it has no input value find associated model and it make the model default values as it is in database.
try to comment the updatemodel line and runt he code... it must work.
It's not a good idea to setup data access this way. One reason is that you should dispose of the db context after you use it. This means that using your method, this leaves the database connection open until garbage collection occurs, which could be minutes or hours later. As other web requests come in, new database connections are created, and again those are not disposed of either.. etc.. etc.. it's a pseudo-memory leak (not a true memory leak because it will eventually get collected, but it means resources are being used well after they are needed)

How to return an overall Model's value as 'null' from ASP.NET MVC model binder

I have an action method that takes several optional parameters.
This ASP.NET MVC actionmethod looks simple enough but isn't working as I want....
[HttpPost]
public ActionResult UpdateOrder(OrderItem OrderItem, Address ShippingAddress)
{
if (ShippingAddress != null) {
// we have a shipping address
}
}
An Address object is always created for ShippingAddress because - well - thats the way model binders work. Even if ShippingAddress.Address1, ShippingAddress.City etc. fields are absent from the Form an object will still be created and passed to the action.
I want a way to make a model binder that returns null for the model if it is deemed to be empty.
A first attempt goes as follows
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
base.OnModelUpdated(controllerContext, bindingContext);
// get the address to validate
var address = (Address)bindingContext.Model;
// if the address is quintessentially null then return null for the model binder
if (address.Address1 == null && address.CountryCode == null && address.City == null)
{
bindingContext.Model = null;
}
}
Unfortunately this simple solution doesn't work and I get the following error:
InvalidOperationException -This property setter is obsolete, because its value is derived from ModelMetadata.Model now.
Is there a way I can make the overall 'Model' from a custom ModelBinder to return null?
Have you tried setting the default parameter to null? You may also need to set the type to nullable as well, but I'm not 100% sure if it's needed, but that's how I use it.
For example:
public ActionResult UpdateOrder(OrderItem OrderItem, Address? shippingAddress = null)
I should probably note that this requires .NET 4, but then, you didn't specify which version you're running on.

Calling UpdateModel with a collection of complex data types reset all non-bound values?

I'm not sure if this is a bug in the DefaultModelBinder class or what.
But UpdateModel usually doesn't change any values of the model except the ones it found a match for.
Take a look at the following:
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Edit(List<int> Ids)
{
// Load list of persons from the database
List<Person> people = GetFromDatabase(Ids);
// shouldn't this update only the Name & Age properties of each Person object
// in the collection and leave the rest of the properties (e.g. Id, Address)
// with their original value (whatever they were when retrieved from the db)
UpdateModel(people, "myPersonPrefix", new string[] { "Name", "Age" });
// ...
}
What happens is UpdateModel creates new Person objects, assign their Name & Age properties from the ValueProvider and put them in the argument List<>, which makes the rest of the properties set to their default initial value (e.g. Id = 0)
so what is going on here?
UPDATE:
I stepped through mvc source code (particularly DefaultModelBinder class) and here is what I found:
The class determines we are trying to bind a collection so it calls the method: UpdateCollection(...) which creates an inner ModelBindingContext that has a null Model property. Afterwards, that context is sent to the method BindComplexModel(...) which checks the Model property for null and creates a new instance of the model type if that is the case.
That's what causes the values to be reset.
And so, only the values that are coming through the form/query string/route data are populated, the rest remains in its initialized state.
I was able to make very few changes to UpdateCollection(...) to fix this problem.
Here is the method with my changes:
internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType) {
IModelBinder elementBinder = Binders.GetBinder(elementType);
// build up a list of items from the request
List<object> modelList = new List<object>();
for (int currentIndex = 0; ; currentIndex++) {
string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);
if (!DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, subIndexKey)) {
// we ran out of elements to pull
break;
}
// **********************************************************
// The DefaultModelBinder shouldn't always create a new
// instance of elementType in the collection we are updating here.
// If an instance already exists, then we should update it, not create a new one.
// **********************************************************
IList containerModel = bindingContext.Model as IList;
object elementModel = null;
if (containerModel != null && currentIndex < containerModel.Count)
{
elementModel = containerModel[currentIndex];
}
//*****************************************************
ModelBindingContext innerContext = new ModelBindingContext() {
Model = elementModel, // assign the Model property
ModelName = subIndexKey,
ModelState = bindingContext.ModelState,
ModelType = elementType,
PropertyFilter = bindingContext.PropertyFilter,
ValueProvider = bindingContext.ValueProvider
};
object thisElement = elementBinder.BindModel(controllerContext, innerContext);
// we need to merge model errors up
VerifyValueUsability(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement);
modelList.Add(thisElement);
}
// if there weren't any elements at all in the request, just return
if (modelList.Count == 0) {
return null;
}
// replace the original collection
object collection = bindingContext.Model;
CollectionHelpers.ReplaceCollection(elementType, collection, modelList);
return collection;
}
Rudi Breedenraed just wrote an excellent post describing this problem and a very helpful solution. He overrides the DefaultModelBinder and then when it comes across a collection to update, it actually updates the item instead of creating it new like the default MVC behavior. With this, UpdateModel() and TryUpdateModel() behavior is consistent with both the root model and any collections.
You just gave me an idea to dig into ASP.NET MVC 2 source code.
I have been struggling with this for two weeks now. I found out that your solution will not work with nested lists. I put a breakpoint in the UpdateCollection method ,and it never gets hit. It seems like the root level of model needs to be a list for this method to be called
This is in short the model I have..I also have one more level of generic lists, but this is just a quick sample..
public class Borrowers
{
public string FirstName{get;set;}
public string LastName{get;set;}
public List<Address> Addresses{get;set;}
}
I guess that, I will need to dig deeper to find out what is going on.
UPDATE:
The UpdateCollection still gets called in asp.net mvc 2, but the problem with the fix above is related to this HERE

Modelbinding database entities in ASPNET MVC

I'm having trouble trying to think what the best way is to recreate a database object in a controller Action.
I want to make use of ModelBinders so in my action I have access to the object via a parameter, rather than having to repeat code to get an object from the database based on an identifier parameter. So I was thinking of having a ModelBinder that performs a call to the dataaccess layer to obtain the original object (or creates a new one if it doesn't exist in the database), then binds any properties to the database object to update it. However I've read that the ModelBinders shouldn't make database queries (first comment of this article).
If the ModelBinder shouldn't perform a database query (so just using the DefaultModelBinder) then what about database objects that have properties that are other db objects? These would never get assigned.
Saving an object after the user has edited it (1 or 2 properties are editable in the view) the ModelBinded object would be missing data, so saving it as it is would result in data in the database being overwritten with invalid values, or NOT-NULL constraints failing.
So, whats the best way to get an object in a controller action from the database bound with the form data posted back from the view?
Note im using NHibernate.
I get the model object from the database, then use UpdateModel (or TryUpdateModel) on the object to update values from the form parameters.
public ActionResult Update( int id )
{
DataContext dc = new DataContext();
MyModel model = dc.MyModels.Where( m => m.ID == id ).SingleOrDefault();
string[] whitelist = new string[] { "Name", "Property1", "Property2" };
if (!TryUpdateModel( model, whitelist )) {
... model error handling...
return View("Edit");
}
ViewData.Model = model;
return View("Show");
}
Unfortunately you don't have control over the construction of the model binder, so you can't inject any repository implementation.
You can reach out directly into a service locator to pull in your repository & fetch the item:
public class ProductBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType)
{
if(modelType != typeof(Product))
return null;
var form = controllerContext.HttpContext.Request.Form;
int id = Int32.Parse(form["Id"]);
if(id == 0)
return base.CreateModel(controllerContext, bindingContext, modelType);
IProductRepository repository = ServiceLocator.Resolve<IProductRepository>();
return repository.Fetch(id);
}
}
You might even make this work for all of your entities if you can use a base class or interface that provides the Id of the class.
You'll have to set this up in Global.asax:
ModelBinders.Binders.Add(typeof(Product), new ProductBinder());
and then you can do this:
public ActionResult Save([Bind] Product product)
{
....
_repository.Save(product);
}
Let me first state that I don't recommend to access database from ModelBinders, as from perspective of Separation Of Concern ModelBinders should only be responsible of interpretting client request, obviously database is not.
If you dont want to repeat your self (DRY), use repositories/services
However if u really want to do it like that, then
In global.asax.cs Register a custom MyModelBinderProvider to MVC
ModelBinderProviders.BinderProviders.Add(new EntityModelBinderProvider
{
ConnectionString = "my connection string"
));
Cunstruct the custom ModelBinderProvider to contain database settings
public class EntityBinderProvider: IModelBinderProvider
{
public string ConnectionString { get; set; }
public IModelBinder GetBinder(Type modelType)
{
if (Is known entity)
return new EntityBinder(ConnectionString);
else
return null;
}
}
Follow further instructions from Ben Scheirman
You don't actually have to hit the database. Simply setting the Id of the objects will be enough to set the relationship up, but watch your cascades. Make sure your cascde settings won't update the related object as it will clear the values.

Resources