MVC How to pass a list of objects with List Items POST action method

后端 未结 2 1781
清酒与你
清酒与你 2020-12-31 17:56

I want to post a List of items to controller from Razor view , but i am getting a List of objects as null My class structre is

Model:

List

        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 18:14

    Change the action method signature to

    public ActionResult OptionalMarks(ICollection model)

    Since in your HTML, it does not look like there is anything named Id in there. This isn't your main issue though.

    Next, do the following with the foor loop

    @for(int idx = 0; idx < Model[item].StudentEntires.Count();idx++)
    {
        @Html.TextBoxFor(_ => Model[item].StudentEntries[idx])
    }
    

    Possibly due to the use of a foreach loop for the StudentEntries, the model binder is having trouble piecing everything together, and thus a NULL is returned.

    EDIT:

    Here's an example:

    Controller

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var viewModel = new IndexViewModel();
    
            var subjects = new List();
            var subject1 = new Subject();
    
            subject1.Name = "History";
            subject1.StudentEntires.Add(new Student { Mark = 50 });
            subjects.Add(subject1);
    
            viewModel.Subjects = subjects;
    
            return View(viewModel);
        }
    
        [HttpPost]
        public ActionResult Index(IndexViewModel viewModel)
        {
            return new EmptyResult();
        }
    }
    

    View

    @model SOWorkbench.Controllers.IndexViewModel
    
    @{
        ViewBag.Title = "Home Page";
    }
    
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        if (Model.Subjects.Any())
        {
            int subjectsCount = Model.Subjects.Count();
            for (int item = 0; item < subjectsCount; item++)
            {
                @Model.Subjects[item].Name
    int studentEntriesCount = Model.Subjects[item].StudentEntires.Count(); for(int idx = 0;idx < studentEntriesCount;idx++) { @Html.TextBoxFor(_ => Model.Subjects[item].StudentEntires[idx].Mark); } }

    } }

    When you post the form, you should see the data come back in the viewModel object.

提交回复
热议问题