简体   繁体   中英

CheckBoxFor resetting the model to null in Razor

I'm iterating a list to set the values for multiple Html.CheckBoxFor controls, but after submitting the form, I get a null value for the model itself in the controller parameter. Should I replace Html.CheckBoxFor with Html.HiddenFor for instance, the whole model binding works and FunctionViewModel is passed to the controller properly.

Model

public class FunctionViewModel
{
    //... (this class is huge)
    public MeasuringViewModel MeasuringViewModel { get; set; }
}

Classes used by the model

public class MeasuringViewModel
{
   //... (this class is also huge)
   public List<BatchItem> BatchToCancel { get; set; }
}

public class BatchItem
{
    public bool IsCancel { get; set; }
    public VMeasuringService VMeasuringService { get; set; }

    public BatchItem(VMeasuringService vMeasuringService)
    {
        IsCancel = false;
        VMeasuringService = vMeasuringService;
    }
}   

Controller

[HttpPost]
public ActionResult CancelBatch(FunctionViewModel viewModel)
{
    // viewModel is null should I use CheckBoxFor

    return View();
}

Form

@using (Html.BeginForm("CancelBatch", "Services", FormMethod.Post, new { Area = "Functions", @id = "cancelForm" }))
{
    for(int i = 0; i < Model.MeasuringViewModel.BatchToCancel.Count; i++)
    {
        @Html.CheckBoxFor(m => m.MeasuringViewModel.BatchToCancel[i].IsCancel)
    }

    <input type="submit" id="btSubmit" title="Post" alt="Post" value="Post" />
}

So, what's wrong with it?

You get null because none of the control ids matching with your model properties, Check by Inspecting your html in browser that, is control ids generated by Razor are matching with your model properties?

secondly in this situation where you cannot give specific ids to your controls then you can get your control value in your controller action using FormCollection like given bellow:

[HttpPost]
public ActionResult CancelBatch(FormCollection fc)
{
    // viewModel is null should I use CheckBoxFor

    return View();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM