1

Suddenly my Create action/view started causing NullReferenceException. Actually it started after migrating to bootstrap twitter 3.

This is the first line that is causing the exception:

@Html.LabelFor(model => model.Name, new { @class = "col-lg-2 control-label" })

Here is my controller code:

        //
        // GET: /Panel/Partners/Create/
        [Authorize]
        public ActionResult Create()
        {
            ViewData["Logo"] = "";

            return View();
        }

Partial view (form):

@model MyApp.Entities.Partner

<fieldset data-listurl="@Url.Action("Index", "Partners", new { Area = "Panel" })" data-removelogo="@Url.Action("RemoveLogo", "Partners", new { Area = "Panel" })">
    <legend>Partners</legend>


    <div class="form-group">
        @Html.LabelFor(model => model.Name, new { @class = "col-lg-2 control-label" })
        <div class="col-lg-10">
            <div class="col-lg-7">
                <input type="text" id="Name" name="Name" value="@Model.Name" class="form-control" />
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Logo, new { @class = "col-lg-2 control-label" })
        <div class="col-lg-10">
            <div id="file-upload">
                <div class="col-lg-9">
                    <span class="">@(ViewData["Logo"] == null || String.IsNullOrWhiteSpace(ViewData["Logo"].ToString()) ? "No file" : ViewData["Logo"].ToString()) </span>

                    <a href="#" class="btn btn-primary select-button">Choose</a>
                </div>
                <input type="file" name="fileUpload" id="fileUpload" style="left: 0; top: -5000px; position: absolute;" />
            </div>@Html.HiddenFor(model => model.Logo)
            <div class="col-lg-9">
                @if (ViewData["Logo"] != null && !String.IsNullOrWhiteSpace(ViewData["Logo"].ToString()))
                {
                    <p><img src="@String.Concat("http://remotepark.blob.core.windows.net/pictures/", ViewData["Logo"])" id="logoView" class="img-thumbnail" style="max-height: 150px" /></p>
                    <p><a href="#" class="btn btn-default remove-button">Remove</a></p>
                }
            </div>
        </div>
    </div>

    <div class="row form-actions">
        <div class="col-lg-12">
            <input type="submit" id="btnSubmit" class="btn btn-primary" value="Save" />
            <input type="button" class="btn" id="btnCancelar" value="Cancel" />
        </div>
    </div>
</fieldset>

Create.cshtml

@model MyApp.Entities.Partner

<div class="panel-middle-top">
    <div class="middle-top-left"></div>
    <div class="middle-top-center">
        <ul class="breadcrumb" style="background-color: transparent;">
            <li><a href="@Url.Action("Index", "Home", new { Area = "Panel" })">Home</a></li>
            <li><a href="@Url.Action("Index", "Partners", new { Area = "Panel" })">Partners</a></li>
            <li class="active">New</li>
        </ul>
    </div>
    <div class="middle-top-right"></div>
</div>
<div class="panel-middle-content">
    @Html.Partial("/Areas/Panel/Views/Shared/_Alerts.cshtml")

    @using (Html.BeginForm("Create", "Partners", 
        FormMethod.Post, 
        new { 
            enctype = "multipart/form-data", 
            id = "partnersForm",
            @class="form-horizontal", 
            rule="form"
        }))
    {
        @Html.Partial("_PartnersForm")
    }
</div>

Model class

public partial class Partner
    {
        #region Primitive Properties

        public int ID { get; set; }

        public string Name { get; set; }

        public string Logo { get; set; }

        /// <summary>
        /// Indicater whether this partner is associated to the current parking lot
        /// </summary>
        public bool Associated { get; set; }

        #endregion

        #region Navigation Properties

        public ICollection<ParkingLot> ParkingLots
        {
            get
            {
                if (_parkingLots == null)
                {
                    var newCollection = new FixupCollection<ParkingLot>();
                    newCollection.CollectionChanged += FixupParkingLots;
                    _parkingLots = newCollection;
                }
                return _parkingLots;
            }
            set
            {
                if (!ReferenceEquals(_parkingLots, value))
                {
                    var previousValue = _parkingLots as FixupCollection<ParkingLot>;
                    if (previousValue != null)
                    {
                        previousValue.CollectionChanged -= FixupParkingLots;
                    }
                    _parkingLots = value;
                    var newValue = value as FixupCollection<ParkingLot>;
                    if (newValue != null)
                    {
                        newValue.CollectionChanged += FixupParkingLots;
                    }
                }
            }
        }
        private ICollection<ParkingLot> _parkingLots;

        #endregion

        #region Association Fixup

        private void FixupParkingLots(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (ParkingLot item in e.NewItems)
                {
                    if (!item.Partners.Contains(this))
                    {
                        item.Partners.Add(this);
                    }
                }
            }

            if (e.OldItems != null)
            {
                foreach (ParkingLot item in e.OldItems)
                {
                    if (item.Partners.Contains(this))
                    {
                        item.Partners.Remove(this);
                    }
                }
            }
        }

        #endregion

    }

Am I missing something?

6
  • modifiy ur quieston with your Model Commented Aug 26, 2013 at 1:58
  • Is it the Action or the View throwing an exception? Commented Aug 26, 2013 at 2:06
  • The Partial View (line 8). Commented Aug 26, 2013 at 2:06
  • Have you tried @Html.Partial("_PartnersForm",Model)? Commented Aug 26, 2013 at 2:14
  • Yes. I tried with and without the Model parameter. Commented Aug 26, 2013 at 2:26

1 Answer 1

1

Looking at the controller code, you are not passing an empty model to the view so there is nothing for the label to bind to hence the null reference exception. I think you need something like the following.

//
        // GET: /Panel/Partners/Create/
        [Authorize]
        public ActionResult Create()
        {
            ViewData["Logo"] = "";
            var model = new MyModel()
            return View(model);
        }

EDIT
I think it is this line of code that is giving you the problem <input type="text" id="Name" name="Name" value="@Model.Name" class="form-control" /> as it is trying to access the Name property of the model which is null if you don't pass anything to the view. Adding the code above gave the view a model to reference and could therefore retrieve the value for the Name property

You are

Sign up to request clarification or add additional context in comments.

2 Comments

It worked, but I have other controllers with the Create action that does not return any instance of my models and they work fine. And as an example, the MVC Music Store sample does not return any instance of the model in the Register action, but it works fine. mvcmusicstore.codeplex.com/SourceControl/latest#MvcMusicStore/…
The problem really was the following line: <input type="text" id="Name" name="Name" value="@Model.Name" class="form-control" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.