Search code examples
c#asp.net-mvc-5

Form value not passed to controller


I have a simple application; given a SpecificationName, it will load all attributes for that SpecificationName.

SamplesController:

public ActionResult Create()
{
     SampleVM samplevm = new SampleVM();

     return View();
}

My Javascript file:

$(function () {
    var Samples = [];

    $('#SpecificationName').change(function () {
        var specificationName = $(this).val();
        var lotId = $('#LotId').val();
        var url = 'https://localhost:44372/Samples/FilterAttributes';
        var queryString = url + '?specificationName=' + specificationName + '&lotId=' = lotId;


        $('#filter-table').load(queryString);
    });
});

It loads the attributes table correctly. But when I submit, nothing is passed to the controller; samples is null:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSamples(List<SampleVM> samples)
{
     if (ModelState.IsValid)
     {
          Sample sample = new Sample();

          db.Samples.Add(sample);

          return RedirectToAction("Create");
      }

      return View(samples);
}

I pass @model IEnumerable<IQC.ViewModels.SampleVM> to both Create.cshtml view and FilterAttributes.cshtml partial view.

What am I doing wrong?

POST payload:

__RequestVerificationToken: some token
item.SpecificationAttributeId: 37627
item.AttributeId: 994
item.Value: 1
item.SpecificationAttributeId: 37628
item.AttributeId: 993
item.Value: 1

The same of it is SaveSamples. Is this the reason why it is not being passed to samples in the controller? Is there a way to change the name?


Solution

  • According to the illustrated payload, it seems that you submit a flatten structure. Thus, it can be only bound to a scalar model value:

    [HttpPost]
    //public ActionResult SaveSamples(List<SampleVM> samples) { ... }
    public ActionResult SaveSamples(SampleVM sample) { ... }
    

    Check this scenario to make sure that it is ok for the scalar model item. If this works, extend your current view part and render an index-ed based inputs names to submit a list-based payload instead of scalar/single, smth like:

    How does MVC 4 List Model Binding work?

    MVC Model Binding with Dynamic Collection