Hamid Reza
Hamid Reza

Reputation: 2973

Object reference not set to an instance of an object on layout page

I have an edit form in an edit page.When I come in the page for the first time everything is OK.But after submitting the form I see 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.

And in the source error you see this:

@{
    ViewBag.Title = "Edit";
    Layout ="~/Views/Shared/_Layout.cshtml";
}

What is wrong now?!

Update

My view codes:

@model Portal.Web.CMS.Models.PageViewModel

@{
    ViewBag.Title = "ویرایش صفحه";
    Layout ="~/Views/Shared/_Layout.cshtml";
}

<h3>صفحه</h3>
<ul class="breadcrumb" style="background-color: white;">
    <li><a href="~/Page">لیست صفحات</a> <span class="divider">/</span></li>
    <li><a href="@Url.Action("Details", "Page", new { url = Model.Url })">@Model.Name</a> <span class="divider">/</span></li>
    <li class="active">ویرایش صفحه</li>
</ul>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    @Html.HiddenFor(model => model.PageId)
    <div class="editor-label">
        @Html.LabelFor(model => model.Lang)
    </div>
    <div class="editor-field">
        <div class="btn-group" data-toggle="buttons-radio" dir="ltr">
            @if (Model.Lang.ToString() == "Fa")
            {
                <button type="button" value="2" class="btn">English</button>
                <button type="button" value="1" class="btn active">فارسی</button>
            }
            else
            {
                <button type="button" value="2" class="btn active">English</button>
                <button type="button" value="1" class="btn">فارسی</button>
            }
        </div>
        @Html.Hidden("Lang")
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

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

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

    <div class="editor-label">
        @Html.LabelFor(model => model.PageContent)
    </div>
    <div class="editor-field">
        @Html.TextAreaFor(model => model.PageContent)
        @Html.ValidationMessageFor(model => model.PageContent)
    </div>
    <div id="attachments" class="editor-field">
        <p>
            <button type="button" id="addFile" class="btn btn success">فایل بیشتر</button>
        </p>
        <p>
            <input type="file" name="files" />
        </p>
    </div>
    <div id="productImages" class="editor-field">
        <p>
            <button type="button" id="addPicture" class="btn btn success">عکس بیشتر</button>
        </p>
        <p>
            <input type="file" name="images" />
        </p>
    </div>
    if (Model.PageAttachements!=null )
    {
    <fieldset>
        <legend>فایل های ضمیمه</legend>
        <div class="row-fluid show-grid">
            @foreach (var file in Model.PageAttachements)
            {
                <div class="span4 thumbnail">
                    <a href="~/Page/DeleteFile/@file.PageAttachmentId" class="close pull-left" onclick="return confirm('آیا میخواهید مورد فوق را حذف نمایید؟')" >&times;</a>
                    @file.Name
                </div>
            }
        </div>
    </fieldset>
    }
    if (Model.PageImages.Count > 0)
    {
    <fieldset>
        <legend>تصاویر ضمیمه</legend>
        <div class="row-fluid show-grid">
            @foreach (var image in Model.PageImages)
            {
                <div class="span4 thumbnail">
                    <a href="~/Product/DeleteImage/@image.PageImageId" class="close pull-left" onclick="return confirm('آیا میخواهید مورد فوق را حذف نمایید؟')" >&times;</a>
                    <img src="~/Images/@image.Name" />
                </div>
            }
        </div>
    </fieldset>
    }
    <p>
        <input type="submit" value="ذخیره" class="btn btn-primary btn-large" />
    </p>
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

And the controller:

public ActionResult Edit(int id)
{
    var model = Mapper.Map<PageViewModel>(pageApp.GetPageById(id));
    return View(model);
}
[HttpPost]
public ActionResult Edit(PageViewModel model)
{
    bool result = false;
    if (model.Lang.ToString() == "Fa")
        result = pageApp.IsRepetitive(model.Url, 1);
    else
        result = pageApp.IsRepetitive(model.Url, 2);
    if (result == true)
    {
        TempData["error"] = "صفحه ای با همین زبان و آدرس وجود دارد.";
        return View();
    }
    else
    {
        if (model.PageContent != null)
        {
            var page = Mapper.Map<Page>(model);
            page.UserId = Portal.Web.CMS.Components.SessionContext.GetUserData().UserId;
            page.PageDate = DateTime.Now;
            pageApp.Update(page);
            TempData["success"] = "صفحه با موفقیت تغییر یافت.";
            return RedirectToAction("Details", new { url = model.Url });
        }
        else
        {
            TempData["error"] = "انجام نشد.صفحه خالی از مطلب است.";
            return View();
        }
    }
}

Upvotes: 0

Views: 9164

Answers (2)

Priyank
Priyank

Reputation: 1384

Because return View(); dose not have Model Object as you have given in Edit like return View(model)

Upvotes: 4

CodingIntrigue
CodingIntrigue

Reputation: 78545

In these lines:

TempData["error"] = "انجام نشد.صفحه خالی از مطلب است.";
return View();

You are returning the Edit view with no model. Hence you get a NullReferenceException when trying to access your model in your view.

You need to return the appropriate model back to the View:

return View(model);

Sidenote: Since you're using strongly-typed models anyway, you might want to add an Error property onto your model instead of using TempData.

Upvotes: 8

Related Questions