我使用 ajax 将部分 View 加载到 View 中。局部 View 中有一个下拉列表,但是每当我选择一个下拉选项并单击局部 View 中的按钮进行连接时,我都会收到一个错误消息,指出模型为空。这很奇怪,因为模型已经填充了下拉列表,并且它不会在断点处对我的 Controller 执行任何操作。我在这上面花了几天时间。
错误是:
An exception of type 'System.NullReferenceException' occurred in App_Web_m2cylvfu.dll but was not handled in user code Additional information: Object reference not set to an instance of an object.
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; }
}
最佳答案
我发现了问题。 javascript 没有在局部 View 中被调用,它直接进入 Controller 操作并返回而不重新加载 viewbag 数据。
关于c# - 单击按钮时模型为空 ASP.NET MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30740849/