Model is null when clicking ASP.NET MVC 5 button
I have uploaded a partial view using ajax in a view. There is a dropdown in the partial view, but whenever I select the dropdown option and click on the button in the partial view to connect, I get an error when the model is null. This is weird because the model is already populated for the dropdown and it doesn't jump to any actions on my controller at the breakpoint. I spent a few days on this.
Mistake:
An exception of type 'System.NullReferenceException' occurred in App_Web_m2cylvfu.dll but was not handled in user code. info: Object reference not set to object instance.
Html
<div>
<fieldset>
<div>
@Html.LabelFor(m => m.ServerName)
</div>
<div>
@Html.DropDownListFor(model => model.ServerName, Model.ServerNames, "-- Select Server --")
</div>
<div>
<input id="btnConnect" type="submit" name="Connect" value="Connect" />
</div>
</fieldset>
</div>
JAVASCRIPT
$(document).ready(function() {
$('#btnConnect').click(function(evt) {
evt.preventDefault();
evt.stopPropagation();
var selectedServerName = $('#ServerName').val()
$.ajax({
url: '@Url.Action("ConnectToServer", "Settings")',
data: {
'servername': selectedServerName
},
cache: false,
type: 'post',
datatype: 'json',
success: function(result) {
var $el = $("#DatabaseName");
$el.empty(); // remove old options
$el.append($("<option></option>").attr("value", '').text('Please Select'));
$.each(result, function(value, key) {
$el.append($("<option></option>").attr("value", value).text(key));
});
}
});
});
}
controller
public PartialViewResult Index() {
var afConnectionModel = new AFConnectionModel() {
ServerNames = GetServers()
};
return PartialView(afConnectionModel);
}
[HttpPost]
public JsonResult ConnectToServer(string servername) {
return Json(new {
foo = "bar", baz = "Blech"
});
}
private static dynamic GetServers() {
var piSystems = new PISystems().Select(c => new Afart {
Id = c.Name, ServerName = c.Name
});
return new SelectList(piSystems, "Id", "ServerName");
}
public class Afart
{
public string Id { get; set; }
public string ServerName { get; set; }
}
+3
source to share
2 answers
it didn't hit the controller because you had some errors in the Javascript code ... try this code
$(document).ready(function() {
$('#btnConnect').click(function(evt) {
evt.preventDefault();
evt.stopPropagation();
var selectedServerName = $('#ServerName').val();
$.ajax({
url: '@Url.Action("ConnectToServer", "Settings")',
data: {
servername: selectedServerName
},
cache: false,
type: 'post',
datatype: 'json',
success: function(result) {
var el = $("#DatabaseName");
el.empty(); // remove old options
el.append($("<option></option>").attr("value", '').text('Please Select'));
$.each(result, function(value, key) {
$el.append($("<option></option>").attr("value", value).text(key));
});
}
});
});
}
0
source to share