I have spent a lot of time trying to sort this out without any luck.
I have successfully created a drop down list and it populates the field and all is well. It even posts the record back to the database. But upon clicking the submit button I get a Null Reference error.
Any and all help would be very appreciated
Below is the Model Code
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
namespace CISIII.Models
{
public class Dropdownlist
{
public DateTime? DtmDate { get; set; }
public List<Status_List>? Statlist2 { get; set; }
public IActionResult? GetDetails { get; set; }
}
public class Status_List
{
public int Id { get; set; }
public string? Description { get; set; }
}
public class UserDataModel
{
public string? Fname { get; set; }
public string? Sname { get; set; }
public string? Coname { get; set; }
public string? Tel { get; set; }
public string? Email { get; set; }
public string? Add1 { get; set; }
public string? Add2 { get; set; }
public string? Suburb { get; set; }
public string? State { get; set; }
public string? Pcode { get; set; }
public string? Findus { get; set; }
public string? Prod_cat { get; set; }
public string? Question2 { get; set; }
public string? Ddlindustry { get; set; }
public string? Web { get; set; }
public string? Statlist1 { get; set; }
public string? Start_date { get; set; }
public string? End_date { get; set; }
public int SaveDetails()
{
SqlConnection con = new SqlConnection("Data Source=bhd-web2;User ID=**;Password=**;Database=***; Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
string query = "INSERT INTO Customers (fname, sname, coname, tel, email, add1, add2, suburb, state, pcode, " +
"findus, prod_cat, question2, ddlindustry, web, status, start_date, end_date, entry_date) values ('" + Fname + "','" + Sname + "','" + Coname + "', " +
"'" + Tel + "','" + Email + "','" + Add1 + "','" + Add2 + "','" + Suburb + "','" + State + "','" + Pcode + "','" + Findus + "','" + Prod_cat + "', " +
"'" + Question2 + "','" + Ddlindustry + "','" + Web + "','" + Statlist1 + "','" + Start_date + "','" + End_date + "', getdate())";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
}
}
Below is the Controller Code
using Microsoft.AspNetCore.Mvc;
using CISIII.Models;
using System.Data.SqlClient;
namespace CISIII.Controllers
{
public class HomeController : Controller
{
public IConfigurationRoot GetConnection()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appSettings.json").Build();
return builder;
}
public IActionResult Index()
{
Dropdownlist multi_Dropdownlist = new Dropdownlist
{
Statlist2 = GetStatusList()
};
return View(multi_Dropdownlist);
}
public List<Status_List> GetStatusList()
{
var connection = GetConnection().GetSection("ConnectionStrings").GetSection("CAS").Value;
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select id, description From status order by description asc;", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<Status_List> status = new List<Status_List>();
if (idr.HasRows)
{
while (idr.Read())
{
status.Add(new Status_List
{
Id = Convert.ToInt32(idr["id"]),
Description = Convert.ToString(idr["description"]),
});
}
}
con.Close();
return status;
}
public IActionResult View1()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
public IActionResult newcust()
{
Dropdownlist multi_Dropdownlist = new Dropdownlist
{
Statlist2 = GetStatusList(),
};
return View(multi_Dropdownlist);
}
[HttpPost]
public IActionResult GetDetails()
{
UserDataModel umodel = new UserDataModel();
umodel.Fname = HttpContext.Request.Form["fname"].ToString();
umodel.Sname = HttpContext.Request.Form["sname"].ToString();
umodel.Coname = HttpContext.Request.Form["coname"].ToString();
umodel.Tel = HttpContext.Request.Form["tel"].ToString();
umodel.Email = HttpContext.Request.Form["email"].ToString();
umodel.Add1 = HttpContext.Request.Form["street_number"].ToString();
umodel.Add2 = HttpContext.Request.Form["route"].ToString();
umodel.Suburb = HttpContext.Request.Form["locality"].ToString();
umodel.State = HttpContext.Request.Form["administrative_area_level_1"].ToString();
umodel.Pcode = HttpContext.Request.Form["postal_code"].ToString();
umodel.Findus = HttpContext.Request.Form["Findlist"].ToString();
umodel.Prod_cat = HttpContext.Request.Form["Prodlist"].ToString();
umodel.Question2 = HttpContext.Request.Form["question2"].ToString();
umodel.Ddlindustry = HttpContext.Request.Form["ddlindustry"].ToString();
umodel.Web = HttpContext.Request.Form["web"].ToString();
umodel.Statlist1 = HttpContext.Request.Form["Statlist"].ToString();
umodel.Start_date = HttpContext.Request.Form["start_date"].ToString();
umodel.End_date = HttpContext.Request.Form["end_date"].ToString();
int result = umodel.SaveDetails();
return View("newcust");
}
}
}
Below is the View
@model CISIII.Models.Dropdownlist
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
ViewData["Title"] = "New Customer";
}
<head>
<table style="margin:0 auto;" >
<tr >
<td ><label>First Name</label></td>
<td >
<input class="field" id="fname" name="fname" TabIndex="1"/>
</td>
<td ><label>Address</label></td>
<td TabIndex="8">
<div id="locationField">
<input id="autocomplete"
placeholder="Enter your address"
onFocus="geolocate()"
type="text"/>
</div>
<td></td>
</td>
</tr>
<tr>
<td ><label>Surname</label></td>
<td >
<input class="field" id="sname" name="sname" TabIndex="2"/></td>
<td ><label>Address 2</label></td>
<td Width="8">
<input class="field" id="street_number" name="street_number" disabled="disabled" />
<input class="field" id="route" name="route" disabled="disabled"/>
</td>
</tr>
<tr>
<td><label>Company Name</label></td>
<td><input class="field" id="coname" name="coname"/></td>
<td><label>Suburb</label></td>
<td>
<input class="field" id="locality" name="locality" disabled="disabled"/>
</td>
</tr>
<tr>
<td><label>Tel No</label></td>
<td>
<input class="field" id="tel" name="tel" TabIndex="4"/></td>
<td><label>State</label></td>
<td>
<input class="field" id="administrative_area_level_1" name="administrative_area_level_1" disabled="disabled"/>
</td>
</tr>
<!-- Communication Details for the Client -->
<tr>
<td ><label>Email</label></td>
<td><input id="email" class="field" name="email" TabIndex="5"/></td>
<td><label>Post Code</label></td>
<td >
<input class="field" id="postal_code" name="postal_code" disabled="disabled"/>
</td>
<!-- OnTextChanged="date_insert" -->
</tr>
<tr>
<td ><label>Web</label></td>
<td >
<input id="web" class="field" name="web" TabIndex="6"></td>
<td ><label>Status</label></td>
<td>
<div id="Status" name="Status">
</div>
<div class="col-md-5">
@Html.DropDownListFor(x => x.Statlist2, new SelectList(Model.Statlist2, "Description", "Description"), htmlAttributes: new { @class = "form-control"})
</div>
</td>
</tr>
<tr >
<td ><label>Start Date</label></td>
<td >
<input id="start_date" name="start_date" class="start_date">
</td>
<td ><label>End Date</label></td>
<td >
<input id="end_date" name="end_date" class="end_date">
</td>
</tr>
<!-- Asking Questions of the client -->
<tr >
<td ColumnSpan="4">
<Label>How did you hear about Us</Label>
</td>
</tr>
<tr >
<td >
<Label>Industry</Label>
</td>
<td ColumnSpan="3" Style="" >
<div class="col-md-3">
</div>
</td>
</tr>
<tr >
<td >
<Label>Product Category</Label>
</td>
</tr>
<tr >
<td >
<Label>Where did you find us</Label>
</td>
</tr>
<tr>
<td ColumnSpan="4" >
<Label>Customer Notes</Label>
</td>
<td ColumnSpan="4" >
<textarea id="question2" class="field" name="question2" cols="40" rows="5"></textarea>
</td>
</tr>
<tr>
<td ColumnSpan="2" ><input id="Submit" type="submit" value="submit" formaction="GetDetails" asp-page-handler="Submit"/>
</td>
</tr>
</table>
</form>
@section Scripts{
<script type="text/javascript">
$(function () {
$(".form-control").chosen();
});
</Script>
<script type="text/javascript">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(".start_date").datepicker({
dateFormat: 'dd/mm/yy',
chanegMonth: true,
changeYear: true,
minDate: new Date(2019,01,01),
maxDate: new Date(2032,01,01),
});
$(".end_date").datepicker({
dateFormat: 'dd/mm/yy',
chanegMonth: true,
changeYear: true,
minDate: new Date(2019,01,01),
maxDate: new Date(2032,01,01),
});
</script>
}
The Error
An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
AspNetCoreGeneratedDocument.Views_Home_newcust.ExecuteAsync() in newcust.cshtml, line 230
Stack Query Cookies Headers Routing
NullReferenceException: Object reference not set to an instance of an object.
AspNetCoreGeneratedDocument.Views_Home_newcust.ExecuteAsync() in newcust.cshtml
@Html.DropDownListFor(x => x.Statlist2, new SelectList(Model.Statlist2, "Description", "Description"), htmlAttributes: new { @class = "form-control"})
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)