I have a page on my MVC application where a user can edit / upload data to a database.
Basically the have a link on the site called “Admin”, they click here, logon and are presented with a page that allows them to change / update data displayed on the “Special Offers” section of the site.
The “Admin” section contains a few textareas which display data contained in a database table. The user can then change the data displayed in these text areas and click an “Update” button which will then upload this data to the database, then the “Special Offers” page in the site displays this newly updated data to the public.
The issue I have is that if the user who is editing the data tries to update the database with textareas that that are empty of data then the “Special Offers” page will not load (it returns an error shown below). I have checked that the database table has the “Nullable” option set to “True”, but this makes no difference.
[Error]
Server Error in ‘/’ Application.
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:
Line 25: @Html.Raw(tbl_special_offers.offer3.Replace(Environment.NewLine, "<br/>"))
This is the code that the “Special Offers” View uses to access the database and display the data (using Visual Web Developer Express):
@model IEnumerable<bhgc.Models.tbl_special_offers>
@{
ViewBag.Title = "Special Offers";
}
<div>
<fieldset>
<legend>Special Offers</legend>
<br />
@foreach (var tbl_special_offers in Model)
{
<div style="overflow: hidden; width: 100%;">
<div style="float: left; width: 40%; height: 50%; margin-left: 50px; border: 1px solid #ddd; padding: 15px;">
@Html.Raw(tbl_special_offers.offer1.Replace(Environment.NewLine, " <br/>"))
</div>
<div style="float: right; width: 40%; height: 50%; margin-right: 50px; border: 1px solid #ddd; padding: 15px;">
@Html.Raw(tbl_special_offers.offer2.Replace(Environment.NewLine, " <br/>"))
</div>
</div>
}
</fieldset>
</div>
Is there anyway to either allow the field to be empty, or automatically append a space into the field when it is updated so that when the public view the “Special Offers” page it doesn’t return an error?
The website and page in question is currently public at http://www.boarsheadgolfcentre.co.uk/Home/Special
Many thanks.
Since the item you are performing a Replace on null, why don’t you try something like this
That way you shouldn’t be replacing on
null, and will (hopefully) avoid the exception.