Mark Jordan
Mark Jordan

Reputation: 37

ASP.NET MVC Web Application - Facing Null Pointer Exception

I am getting this exception whenever I try to call this redirect link on Employee data Image. Any help which could solve this problem is much appreciated.

My Work:

Employee View empRecords:

@using PagedList.Mvc;
@using PagedList;
@model IPagedList<My_Work.Models.Employee>
@{
    HttpCookie cookie = Request.Cookies["Detalis"];
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EmpRecords</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div style="float:left">
        @Html.ActionLink("Create New", "Create")
    </div>
    <div style="float:right">
        @{
            String img64 = (string)Session["userImage"];
            String img64Url = string.Format("data:image/" +
           (string)Session["userImageType"] + ";base64,{0}", img64);
            //imagetype can be e.g. gif, jpeg, png etc.
        }
        <img alt="" src="@img64Url" width="45" height="80"
             class="rounded-circle" />
        <br />
        @Html.ActionLink("Click to Logout", "Logout", "User")
    </div>
    <br />
    <p>

        @Html.Partial("_EmployeeInfo", Model)
    </p>
    <br />
    <div style="float:left">
        <dl>
            <dt>
                @Html.ActionLink("User Last Login:", cookie["Lastlogin"])
            </dt>
            <dd>
                @if (cookie != null)
                {
                    @cookie["Lastlogin"];
                }
            </dd>
        </dl>
    </div>
    <br />
</body>
</html>

Partial Layout View _EmployeeInfo:

@using PagedList.Mvc;
@using PagedList;
@model IPagedList<My_Work.Models.Employee>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.First().EmployeeID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().ImageURL)
        </th>
        <th>
            Image
        </th>
    </tr>
    @if (Model.Count() == 0)
    {
        <tr>
            <td colspan="6">
                No records match search criteria
            </td>
        </tr>
    }
    else
    {
        foreach (var item in Model)
        {
            using (Html.BeginForm("Delete", "Employee", new
            {
                id =
           item.EmployeeID
            }))
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.EmployeeID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem =>
                       item.FirstName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ImageURL)
                    </td>
                    <td>
                        @if (!string.IsNullOrEmpty(item.ImageURL))
                         {
                           <a href="/Employee/Details">
                              @*@Url.Content convert the relative path into application absolute path*@
                              <img src="@Url.Content("~/Images/" + item.ImageURL)" height="50px" width="50px" />
                           </a>
                         }
                         else
                         {
                            <span>No Image Found!</span>
                         }
                    </td>
                </tr>
            }
        }
    }
</table>
@Html.PagedListPager(Model, page => Url.Action("empRecords", new { page,
SearchBy = Request.QueryString["SearchBy"], SearchTerm =
Request.QueryString["SearchTerm"], sortBy =
Request.QueryString["sortBy"] }), new PagedListRenderOptions() {
Display = PagedListDisplayMode.IfNeeded,
DisplayPageCountAndCurrentLocation = true })

so, the main problem is that whenever I tried to call this redirect link I faced this error:

Code:

@if (!string.IsNullOrEmpty(item.ImageURL))
{
    <a href="/Employee/Details">
        @*@Url.Content convert the relative path into application absolute path*@
        <img src="@Url.Content("~/Images/" + item.ImageURL)" height="50px" width="50px" />
    </a>
}

Error Message:

enter image description here

Employee Controller functions used for following task:

public ActionResult empRecords(string SearchBy, string SearchTerm, int? page, string sortBy)
{
    //In case of Invalid user redirect to login
    if (Session["login"] == null)
    {
        return RedirectToAction("Login", "User");
    }
    EmployeeEntity entity = new EmployeeEntity();
    List<Employee> list = entity.GetList(SearchBy,SearchTerm, sortBy);
    HttpCookie cookie = Request.Cookies["Detalis"];
    if (cookie != null)
    {
        string color = cookie["Lastlogin"];
    }

    return View(list.ToPagedList(page ?? 1, 5));
}

public ActionResult Details(long id)
{
    //In case of Invalid user redirect to login
    if (Session["login"] == null)
    {
        return RedirectToAction("Login", "User");
    }
    EmployeeEntity entity = new EmployeeEntity();
    Employee employee = entity.GetSingleEmployee(id);
    HttpCookie cookie = Request.Cookies["Detalis"];
    if (cookie != null)
    {
        string color = cookie["Lastlogin"];
    }
    return View(employee);

}

Employee View Details:

@model My_Work.Models.Employee
@{
    Layout = null;
    HttpCookie cookie = Request.Cookies["Detalis"];
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Employee Detail</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div>
        <h4>Employee Detail</h4>
        <hr />
        <dl class="dl-horizontal">
            <dt>
                @Html.DisplayNameFor(model => model.EmployeeID)
            </dt>

            <dd>
                @Html.DisplayFor(model => model.EmployeeID)
            </dd>
            <dt>
                @Html.DisplayNameFor(model => model.FirstName)
            </dt>

            <dd>
                @Html.DisplayFor(model => model.FirstName)
            </dd>

            <dt>
                @Html.DisplayNameFor(model => model.LastName)
            </dt>

            <dd>
                @Html.DisplayFor(model => model.LastName)
            </dd>
            <dd>
                @{
                    String img64 = (string)Session["userImage"];
                    String img64Url = string.Format("data:image/" +
                   (string)Session["userImageType"] + ";base64,{0}", img64);
                    //imagetype can be e.g. gif, jpeg, png etc.
                }
                <img alt="" src="@img64Url" width="45" height="80"
                     class="rounded-circle" />
            </dd>
        </dl>
    </div>
    <p>
        @Html.ActionLink("Edit", "Edit", new { id = Model.EmployeeID
       }) |
        @Html.ActionLink("Back to List", "empRecords")
    </p>
</body>
</html>

Upvotes: 0

Views: 863

Answers (2)

Thomson Mixab
Thomson Mixab

Reputation: 657

Additional note, you can also make the id parameter not mandatory, then It will not give you null pointer exception. In your code, you will need to add some validation code if you are expecting id parameter can not be null.

public ActionResult Details(long? id = null)
{
    // validation code example
    if (!id.HasValue)
    {
        // Redirect or return the appropriate HTTP code here
    }

    //In case of Invalid user redirect to login
    if (Session["login"] == null)
    {
        return RedirectToAction("Login", "User");
    }
    EmployeeEntity entity = new EmployeeEntity();
    Employee employee = entity.GetSingleEmployee(id);
    HttpCookie cookie = Request.Cookies["Detalis"];
    if (cookie != null)
    {
        string color = cookie["Lastlogin"];
    }
    return View(employee);

}

Upvotes: 1

Yong Shun
Yong Shun

Reputation: 51135

ISSUE

You get the above error as id is the mandatory parameter in Details function (action) in Employee controller.

<a href="/Employee/Details">
    @*@Url.Content convert the relative path into application absolute path*@
    <img src="@Url.Content("~/Images/" + item.ImageURL)" height="50px" width="50px" />
</a>

SOLUTION

You have to make sure that id must be included in the URL for redirecting to Employee/Details.

The URL should be as below:

/Employee/Details/{id}

SOLUTION 1:

<a href="/Employee/Details/@item.EmployeeID">
    @*@Url.Content convert the relative path into application absolute path*@
    <img src="@Url.Content("~/Images/" + item.ImageURL)" height="50px" width="50px" />
</a>

SOLUTION 2:

<a href="@Url.Action("Details", "Employee", new { id = item.EmployeeID})">
    @*@Url.Content convert the relative path into application absolute path*@
    <img src="@Url.Content("~/Images/" + item.ImageURL)" height="50px" width="50px" />
</a>

Upvotes: 1

Related Questions