0

i have the following code for view:

@model test1.Models.CustomerVM

@{
    ViewBag.Title = "Create";
}
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Customer</legend>

        @Html.HiddenFor(model=>model.UserId)
        @Html.HiddenFor(model=>model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.User)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User)
            @Html.ValidationMessageFor(model => model.User)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ConfirmPassword)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.ConfirmPassword)
            @Html.ValidationMessageFor(model => model.ConfirmPassword)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.NameTitle)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
            @Html.ValidationMessageFor(model => model.NameTitle)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.FName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FName)
            @Html.ValidationMessageFor(model => model.FName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LName)
            @Html.ValidationMessageFor(model => model.LName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Gender, Model.GenderColl)
            @Html.ValidationMessageFor(model => model.Gender)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DOB)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DOB)
            @Html.ValidationMessageFor(model => model.DOB)
        </div>

        @* contacts *@
             <div class="editor-label">
            @Html.LabelFor(model => model.AddressL1)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.AddressL1)
            @Html.ValidationMessageFor(model => model.AddressL1)
        </div>

             <div class="editor-label">
            @Html.LabelFor(model => model.AddressL2)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.AddressL2)
            @Html.ValidationMessageFor(model => model.AddressL2)
        </div>

             <div class="editor-label">
            @Html.LabelFor(model => model.Suburb)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Suburb)
            @Html.ValidationMessageFor(model => model.Suburb)
        </div>

             <div class="editor-label">
            @Html.LabelFor(model => model.Country)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Country)
            @Html.ValidationMessageFor(model => model.Country)
        </div>

             <div class="editor-label">
            @Html.LabelFor(model => model.Phone)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Phone)
            @Html.ValidationMessageFor(model => model.Phone)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {

    <script src="~/Scripts/jquery-2.1.4.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>

    @Scripts.Render("~/bundles/jqueryval")

    <script>
        $(document).ready(function () {
            $('#DOB').datepicker({
                appendText: 'mm/dd/yyyy',
                showOn: 'both',
                buttonText: 'click me',
                dateFormat: 'mm/dd/yy',
                changeMonth: 'true',
                changeYear: 'true',
                yearRange: '1900:2016'
            });
        });
    </script>

}

the view works fine displays data as it should be. but when i click Create to save record the following error throws : Object reference not set to an instance of an object This is thrown when it executes the line db.SaveChanges();

Here is the action that does the save. Note: though the view has more field but im not saving all only the ones i have stated in Create() will be saved a.k.a only data in mst_users will be saved

    [HttpPost]
    public ActionResult Create(CustomerVM custObject)
    {

            if (ModelState.IsValid)
            {
                mst_users user = new mst_users 
                { 
                    uName=custObject.User, 
                    password=custObject.Password, 
                    dtCreated=DateTime.UtcNow, 
                    isLocked=false
                };

                db.mst_users.Add(user);
                db.SaveChanges();
         }
   }

when i check the receiving data to the method it has all the required data to do the save but funny thing is when it throws the exception the debugger takes the control to the the view and points to the NameTitle field.

Line 44:         </div>
Line 45:         <div class="editor-field">
Line 46:             @Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
Line 47:             @Html.ValidationMessageFor(model => model.NameTitle)
Line 48:         </div>

here is the table that maps to Entity class mst_users

 [uName] varchar
 [password] varchar
 [dtCreated] datetime
 [dtUpdated] datetime
 [isLocked] bit

here is the entity class:

enter image description here

here is the video

Here is a null reference error video

Phill Greggan
  • 2,234
  • 3
  • 20
  • 33
  • Can you provide the class **mst_users**? – Shittu Joseph Olugbenga Dec 28 '15 at 11:34
  • @ShittuJosephOlugbenga its an Entity class – Phill Greggan Dec 28 '15 at 11:41
  • Yes i know. I want to see what it contains. I only want to see all the fields it contains. – Shittu Joseph Olugbenga Dec 28 '15 at 11:45
  • What do you return from your `create` method? can you please show the full/actual code of your `create` action? – Zeeshan Dec 28 '15 at 11:47
  • @Zeeshan its the actual code 'cus i have commented the other code lines – Phill Greggan Dec 28 '15 at 11:49
  • In that case, I'm sure your `mst_users` table is successfully populated, even if this exception occurs. right? can you check your table and let me know, if values are being inserted properly, even if exception occurs – Zeeshan Dec 28 '15 at 11:53
  • and I don't think it is the final code. Can you successfully compile it without errors? because your `Create` action signature says that it should return something. but i don't see any `return` word in your action. Please compile it again as it is mentioned above – Zeeshan Dec 28 '15 at 11:56
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeCaster Dec 28 '15 at 12:10
  • So your title doesn't match your problem anymore. Try debugging and searching. Just inspect the ModelState and you'll find why it is invalid. – CodeCaster Dec 28 '15 at 12:20

3 Answers3

1

As you stated that:

but funny thing is when it throws the exception the debugger takes the control to the the view and points to the NameTitle field.

The problem is not exactly at SaveChanges(), but the exception actually occurs when your action is successfully executed and your same Create view is rendered again. This time, your Model or Model.NameTitleColl is null.

When you make get call to your Create action, you must be populating your CustomerVM method and returning it to view. But after making POST call call to your Create method, if you want to render the same view again, you must populate your CustomerVM again, at the end, and pass it to the view. something like:

[HttpPost]
public ActionResult Create(CustomerVM custObject)
{

        if (ModelState.IsValid)
        {
            mst_users user = new mst_users 
            { 
                uName=custObject.User, 
                password=custObject.Password, 
                dtCreated=DateTime.UtcNow, 
                isLocked=false
            };

            db.mst_users.Add(user);
            db.SaveChanges();
     }

    return View(custObject);
    //or return View(new CustomerVM()) just to make you understand

}

UPDATE: (based on video you attached)

You are only populating User, Password and ConfirmPassword field of your CustomerVM model. And you have decorated your Address, Fname and several other properties with *[Required]* attribute. Which means, it MUST not be null when posted, (in order to make model valid). Otherwise, your model state would be invalid. You can clearly see in video, custObject contains null for required values. so exactly as expected, you ModelState.IsValid will give you false in return.

UPDATE: (based on second video you attached) You are right, your exception occurs at db.SaveChanges() line. The reason for why your debugger takes you to view is following piece of code in your action:

try
{
   ....
   db.SaveChanges();
 }
 catch()
 {
   return View(); // <- this line
 }

so technically, exception occurs, and the control of your program is moved to your catch block. and you execute return View() in order to handle your exception and when view is rendered, Model.NameTitleColl is null. This throws another exception, which you actually see. whereas, you have skipped the orignal exception.

Reason and Solution:

From your code, I can see, you do not initialize your db object in your action, which throws the orignal exception. Please initialize the db object before you perform any action on it. You can do something like:

db = new YourDbContextNameHere(); //initialize your db object with your Dbcontext class constructor

and then do:

db.mst_users.Add(user);
db.SaveChanges();

it will work fine this way.

Zeeshan
  • 2,884
  • 3
  • 28
  • 47
0

This NullPointerException is thrown for db or db.mst_users? In my opinion any one of them is not properly Instantiated.

inampaki
  • 159
  • 1
  • 4
0

Based on @Zeeshan answer, I presume your mst_users is being saved to the database the very first time you click the Create button. The problem is likely to be that you are returning same view without passing in the appropriate model that contains the Model.NameTitleColl which is used to populate the dropdown. Hence, the NullExpception.

Update 1 Your model will be invalid because most of your required fields in CustomerVM are null.

For example the following required field LName, FName etc are all null. in your video, this values are not provided in the view.

Shittu Joseph Olugbenga
  • 6,396
  • 5
  • 26
  • 37