This question already has an answer here:

I am trying to avoid using Html.CheckBoxFor in MVC 5 because of the extra hidden input that is added into the DOM. Reason being i am using a template and the extra input kills the lovely css'd checkbox styling.

when doing this:

<input type="checkbox" 
id="@Html.IdFor(m => m.RememberMe)" 
name="@Html.NameFor(m => m.RememberMe)" 
value="true" checked="@(Model.RememberMe ? " checked" : String.Empty)" />

This question already has an answer here:

I am trying to add values to dictionary. Here is my code :-

public class EmpModel
{
    ....
    public Dictionary<String, String> EmpColumns { get; set; }
}

Controller

EmpModel model = new EmpModel();
model.EmpColumns.Add("one", "1"); // It gives error here

An exception of type

System.NullReferenceException

Why i am getting this error? How to solve this?

This question already has an answer here:

i am getting a strange error in a Web applicaton mvc project, in razor view i am getting NullReferenceException even object is not null.

here is link of screenshot of error. [screenshot of error] http://i.stack.imgur.com/eL8HQ.png

Things those i already tried:

  1. Cleaned/Rebuild solution and project.
  2. Deleted Temporary ASP.NET Files.
  3. Deleted View, Renamed View.
  4. Deleted Obj folder.
  5. Changed build config to Debug/Release.

None of these helped.

Please help me to solve this.

This question already has an answer here:

creating a login form however when comparing the username and password in database to allow access am ending up with this error.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

at this line,

SqlCommand cmd3 = new SqlCommand("Select id,Username,
                                  Password from User_data 
                                  where Username='"+UserName.Text.Trim()+"'",con);

below is my code,

protected void button1_click(Object sender, EventArgs e)
{
    SqlCommand cmd3 = new SqlCommand("Select id,Username,Password from User_data where Username='"+UserName.Text.Trim()+"'",con);

    dr = cmd3.ExecuteReader();
    dr.Read();

    string id = dr[0].ToString();
    string un=dr[1].ToString();
    string pwd= dr[2].ToString();

    dr.Close();

    con.Close();
}

This question already has an answer here:

Line 19:     
static BalloonShopConnectionString1()

Line 20:  
   {

Line 21:
         dbConnectionString = ConfigurationManager.ConnectionStrings["BalloonShopConnection"].ConnectionString;

Line 22:
         dbProviderName = ConfigurationManager.ConnectionStrings["BalloonShopConnection"].ProviderName;

Line 23:         productsPerPage = System.Int32.Parse(ConfigurationManager.AppSettings["ProductsPerPage"]);

Line 21 Error

This question already has an answer here:

I've noticed that one of my ASP.NET MVC apps started generating a NullReferenceException error when a custom error message is added to the model state. When that happens, I end up getting an error on one of the Html.TextBoxFor calls the view uses. The controller looks like this:

public async Task<ActionResult> ConfirmPayment(PaymentInfo model){
  try{
    //this will generate an exception
    PaymentManager.Pay(...);
  }
  catch(PaymentException ex){
   _logger.Error(ex);
   var field = MapErrorToField(ex); //this returns the name of one of the fields
   ModelState.AddModelError(field, "error");
  }

I've found some links that suggested the problem could be solved by calling SetModelValue. Unfortunately, that did not solve my problem.

Any help?

This question already has an answer here:

I am getting this error, and it points me to this code:

private int getPlaces(string id)
    {
        string strConnectionString = ConfigurationManager.ConnectionStrings["SilverInfocomm"].ConnectionString;
        SqlConnection myConnect = new SqlConnection(strConnectionString);
        string sql = "SELECT Places FROM SIJ WHERE ID='" + id + "'";
        SqlCommand cmd = new SqlCommand(sql, myConnect);
        myConnect.Open();
        int numrows = (int)cmd.ExecuteScalar();
        myConnect.Close();
        return numrows;
    }

Please help :-(

This question already has an answer here:

I am trying to assign a simple string variable to a class attribute and it is throws exception saying. ERROR: Object reference not set to an instance of an object.

Is don't get it, what is wrong the values are there, but if i check them in isNull it returns false. Please help me understand this issue.

Code Snippet:

    private void SetData()
    {
        string time = tsMeeting.Hour + ":" + tsMeeting.Minute + ":" + tsMeeting.Second+" "+tsMeeting.AmPm;
        string date = calMeeting.SelectedDate.Year + "/" + calMeeting.SelectedDate.Month + "/" + calMeeting.SelectedDate.Day;

       // if (String.IsNullOrEmpty((date + " " + time).Trim()))
        //{
            meeting.MeetingTime = date + " " + time;
            meeting.Edit();
        //}
    }  

This question already has an answer here:

After Logout from Application when i am trying to access home page without login and click on any menue item.

public ActionResult StudentList()
{
    if (UserRole.Students == 0)
        return RedirectToAction("Index", "Home");

    StudentRepo strepo = new StudentRepo();
    List<tblStudent> stdlist = strepo.getstudentlist();
    ViewBag.stdlist = stdlist;
    return View();
}

This question already has an answer here:

I am using ASP.NET MVC 5 with Identity 2, After I published the App to IIS 7 (Windows Server 2008 R2).

The Works find for a while then (I think After the first Session expires) I get this Error :

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
O8.WEB.Controllers.AccountController.Login(String returnUrl) +715
lambda_method(Closure , ControllerBase , Object[] ) +126

System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +216 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +38 System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +11 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +138 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +111 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +32 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +231 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +111 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +19 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +111 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

I have twice now seen a NullReferenceException logged from a Production ASP.NET MVC 4 web application - and logged on the wrong line. Not wrong by a line or two (like you would get with a PDB mismatch), but wrong by the length of the entire controller action. Example:

public ActionResult Index()
{
    var someObject = GetObjectFromService();
    if (someObject.SomeProperty == "X") { // NullReferenceException here if someObject == null
        // do something
    }

    // about 40 more lines of code

    return View();    // Stack trace shows NullReferenceException here
}

This has happened twice for actions on the same controller. The second case was logged on

// someObject is known non-null because of earlier dereferences
return someObject.OtherProperty
    ? RedirecToAction("ViewName", "ControllerName")
    : RedirectToAction("OtherView", "OtherController");

This is very disturbing. NullReferenceException is very easy to fix once you know what line it occurs on. It's not quite so easy if the exception could have happened anywhere within the controller action!

Has anyone ever seen anything like this at all, either in ASP.NET MVC or elsewhere? I'm willing to believe it's the difference between a Release build and a Debug build, but still, to be off by 40 lines?


EDIT:

To be clear: I'm the original author of "What is a NullReferenceException and how do I fix it?". I know what a NullReferenceException is. This question is about why could the stack trace be so far off. I have seen cases where a stack trace is off by a line or two due to PDB mismatch. I have seen cases where there is no PDB, so you don't get line numbers. But I have never seen a case where the stack trace is off by 32 lines.

EDIT 2:

Note that this has happened with two separate controller actions within the same controller. Their code is quite different from each other. In fact, in the first case, the NullReferenceException didn't even occur in a conditional - it was more like this:

SomeMethod(someObject.SomeProperty);

There was some chance that the code had been reorganized during optimization so that the actual NullReferenceException occurred closer to the return, and the PDB was in fact only off by a few lines. But I don't see an opportunity to rearrange a method call in a way that would cause the code to move by 32 lines. In fact, I just looked at the decompiled source, and it does not appear to have been rearranged.

What these two cases have in common are:

  1. They occur in the same controller (so far)
  2. In both cases, the stack trace points to the return statement, and in both cases, the NullReferenceException occurred 30 or more lines away from the return statement.

EDIT 3:

I just did an experiment - I just rebuilt the solution using the "Production" build configuration that we have deployed to our Production servers. I ran the solution on my local IIS, without changing the IIS configuration at all.

The stack trace showed the correct line number.