简体   繁体   English

CheckBox 用于在 Razor 中将模型重置为 null

[英]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.我正在迭代一个列表来设置多个Html.CheckBoxFor控件的值,但是在提交表单后,我在控制器参数中得到模型本身的空值。 Should I replace Html.CheckBoxFor with Html.HiddenFor for instance, the whole model binding works and FunctionViewModel is passed to the controller properly.例如,我是否应该用Html.HiddenFor替换Html.CheckBoxFor ,整个模型绑定工作并且FunctionViewModel正确传递给控制器​​。

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?您得到 null 是因为没有与您的模型属性匹配的控件 ID,通过在浏览器中检查您的 html 来检查 Razor 生成的控件 ID 是否与您的模型属性匹配?

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:其次,在这种情况下,您无法为控件提供特定的 id,那么您可以使用 FormCollection 在控制器操作中获取控件值,如下所示:

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

    return View();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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