Click here to Skip to main content
15,867,862 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am having this exception... can anyone please help to remove it....
Doing my task in asp.net mvc
Here is my code

Create View.....
@model SampleWeb.Models.CreateUser

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>CreateUser</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>

        <fieldset>
            <legend>
                <h3>
                    Roles Associated with this User
                </h3>
            </legend>
            <div class="panel" id="RolesTable">
                @Html.Partial("_AddUserRole", Model)
            </div>
           
            
        </fieldset>  

    </div>
}

PArtial View.....
<pre>@model DTO.UserDTO

@{if (Model.Role.Count == 0)
{
    <h2><font color="red">No Associated Roles...</font></h2>
    <br />
}
else
{
    <table id="RoleTable" style="width: 65%">
        <thead>
        <th style="width: 90%">
            Role
        </th>
        <th>
            Action
        </th>
        </thead>
        @foreach (var role in Model.Role.OrderBy(r => r.Description))
        {
            <tr>
                <td>
                    @Html.ActionLink(role.RoleName, "RoleDetails", new { id = role.RoleID })
                </td>
                @*<td>
                    <center><img class="bin" src="@Url.Content("~/Content/images/bin.png")" alt="Delete" id="@role.Role_Id" /></center>
                </td>*@
            </tr>
        }
    </table>
    <br />
}
}


UserDTO class....
public class UserDTO
    {
        public int UserID { get; set; }
        public string UserName { get; set; }

        public virtual ICollection<RoleDTO> Role { get; set; }
    }


Action in Controller...
public PartialViewResult AddUserRole(int id, int userId)
       {

           RoleDTO role = new RoleDTO();
           role.RoleID = id;
           UserDTO user = new UserDTO();
           user.UserID = userId;

           new UserHandler().AddUserRoles(id, userId);
           return PartialView("_AddUserRole", userId);
       }


<pre lang="xml">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:


Line 1: @model DTO.UserDTO
Line 2:
Line 3: @{if (Model.Role.Count == 0)
Line 4: {
Line 5: &lt;h2&gt;&lt;font color=&quot;red&quot;&gt;No Associated Roles...&lt;/font&gt;&lt;/h2&gt;

Source File: f:\DOT NET WORKINGS\SamplePrivilige\SampleWeb\Views\User\_AddUserRole.cshtml Line: 3

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_User__AddUserRole_cshtml.Execute() in f:\DOT NET WORKINGS\SamplePrivilige\SampleWeb\Views\User\_AddUserRole.cshtml:3
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +252
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +147
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +121
System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) +136
ASP._Page_Views_User_Create_cshtml.Execute() in f:\DOT NET WORKINGS\SamplePrivilige\SampleWeb\Views\User\Create.cshtml:39
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +252
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +147
System.Web.WebPages.StartPage.ExecutePageHierarchy() +88
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +106
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +374
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +89
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +833
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
System.Web.Mvc.Async.&lt;&gt;c__DisplayClass21.&lt;BeginInvokeAction&gt;b__1e(IAsyncResult asyncResult) +186
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.Controller.&lt;BeginExecuteCore&gt;b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.&lt;BeginProcessRequest&gt;b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +67
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +137
</pre>
Posted
Updated 25-Oct-22 0:26am

I don't see how your code works at all, your view expects a model of DTO.UserDTO but you are passing it an int. Try

return PartialView("_AddUserRole", user);


Other than that either Model is null or Role is null

http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it[^]
 
Share this answer
 
The _AddUserRole partial view clearly expects UserDTO as model but you are passing userId, an integer, instead. This should work better:
C#
return PartialView("_AddUserRole", user);

I guess you also want to add the newly created role to the user but I leave that to you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900