【发布时间】:2022-02-02 19:04:36
【问题描述】:
在我的项目中,我有一个带有 2 个下拉列表并通过单击按钮的表单 它应该在数据库中搜索并返回结果列表。此下拉列表也可以为空。 每次我单击按钮并通过 ajax 将值发送到我的控制器时 它为我的所有值显示此错误:
对象引用未设置为对象的实例。
这是我的 ajax 代码:
var ValCourse = $("#ddlCourseName").val();
var ValTeacher = $("#ddlTeachers").val();
var CurrentCourseModel = {
CourseNameID: ValCourse,
CourseTeacherID: ValTeacher,
}
var viewModel = {
"CurrentCourseModel": CurrentCourseModel
}
$.ajax({
type: "POST",
url: UrlFindCourse,
data: JSON.stringify(viewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (response) {
alert("Success");
}
error: function (response) {
alert("Error");
}
});
这是我的 ActionResut:
public ActionResult Courses(CourseModelView viewModel)
{
try
{
CourseRepository repository = new CourseRepository();
CourseModelView model = new CourseModelView();
model.CurrentCourseModel.CourseNameID = viewModel.CurrentCourseModel.CourseNameID;
model.CurrentCourseModel.CourseTeacherID = viewModel.CurrentCourseModel.CourseTeacherID;
model.CurrentCourseModels = repository.FindCourse(model.CurrentCourseModel);
return View(model);
}
catch (Exception Err)
{
LogRepository.Logs.WriteDebug(Err, "error");
return View("~/ HttpError / 500.html");
}
}
ajax 正确接收了我测试过的所有值。 但操作结果说我所有的值都是空的 请帮我 谢谢
【问题讨论】:
-
如果使用 AJAX,我建议使用 ApiController 而不是 Controller。请查看docs.microsoft.com/en-us/aspnet/web-api/overview/…
标签: c# ajax asp.net-mvc