使用jQuery Ajax将View Viewmodel发布到控制器,但模型为null

时间:2016-07-07 12:52:27

标签: jquery ajax null asp.net-mvc-viewmodel

Student.cs

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }        
    public string Class { get; set; }
}

public class StudentViewModel
{
    public Student Student { get; set; }
    public List<string> SelectedClass { get; set; }
    public List<SelectListItem> ClassList { get; set; }
}

我的控制器StudentController

  public class StudentController : Controller
{
    //
    // GET: /Student/

    public ActionResult Index()
    {
        var student = new Student { 
            StudentId = 1, 
            StudentName = "Himen Suthar"                 };

        var classList = new List<SelectListItem>();
        classList.Add(new SelectListItem {Text  = "Std 8" ,Value = "1"});
        classList.Add(new SelectListItem { Text = "Std 9", Value = "2" });
        classList.Add(new SelectListItem { Text = "Std 10", Value = "3" });

        var viewModel = new StudentViewModel();
        viewModel.Student = student;
        viewModel.ClassList = classList;

        return View(viewModel);
    }


    [HttpPost]
    public ActionResult Index(StudentViewModel model)
    {
        if (ModelState.IsValid)
        { 

        }


        var classList = new List<SelectListItem>();
        classList.Add(new SelectListItem { Text = "Std 8", Value = "1" });
        classList.Add(new SelectListItem { Text = "Std 9", Value = "2" });
        classList.Add(new SelectListItem { Text = "Std 10", Value = "3" });



        model.ClassList = classList;

        return View(model);
    }

}

指数:

Index.cshtml

我在索引页面上有列表框,当我更改列表框值时,它会将模型发布到Controller,但我得到View模型的空值,但模型状态是有效的。请指导做秀。

ViewModel为null:

ViewModel is null

2 个答案:

答案 0 :(得分:0)

为此,您可以参考此链接将模型的值从控制器传递到视图,以便您可以获取数据 http://www.codeproject.com/Articles/786604/Passing-data-from-Controller-to-View-in-ASP-NET-MV

答案 1 :(得分:0)

你的json有一些问题

您提供的内容与此类def相匹配。请注意学生是如何收藏的。也因为包围'[',']'你实际上有一个List&lt; StudentViewModel&GT;进入帖子而不是单个StudentViewModel。您也无法使用该json将classlist映射到SelectListItem。

public class Student
{
    public string StudentId { get; set; }
    public string StudentName { get; set; }
    public string Class { get; set; }
}

public class ClassList
{
}

public class StudentViewModel 
{
    public List<Student> Student { get; set; }
    public string SelectedClass { get; set; }
    public List<ClassList> ClassList { get; set; }
}