【问题标题】:ActionResult parameter is nullActionResult 参数为空
【发布时间】: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 正确接收了我测试过的所有值。 但操作结果说我所有的值都是空的 请帮我 谢谢

【问题讨论】:

标签: c# ajax asp.net-mvc


【解决方案1】:

你最好为 ajax 创建一个特殊的视图模型

public class ViewModel
{
  public int CourseNameID {get; set;}
  public int CourseTeacherID {get; set;}
}

试试这个 ajax

$.ajax({
        type: "POST",
        url: UrlFindCourse,
        data: { viewModel:viewModel},
        success: function (response) {
                alert("Success");
        }
        error: function (response) {
            alert("Error");
        }
    });

并修复动作

 public ActionResult Courses(ViewModel viewModel)
 {
 CourseModelView model = new CourseModelView{ CurrentCourseModel=new CurrentCourseModel()};

model.CurrentCourseModel.CourseNameID = viewModel.CourseNameID;
model.CurrentCourseModel.CourseTeacherID = viewModel.CourseTeacherID;
model.CurrentCourseModels = repository.FindCourse(model.CurrentCourseModel);

PS。我不得不猜测编写这段代码。请发布 CourseModelView 课程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    相关资源
    最近更新 更多