【问题标题】:I am getting null value in the server side from CheckBox in asp.net MVC我从 asp.net MVC 中的 CheckBox 获取服务器端的空值
【发布时间】:2022-01-11 03:04:20
【问题描述】:

当我选中该框时,它显示它在服务器端模型中有一个错误值,但在获取值的 ajax 调用中它显示空值。

在模型类中:

[Display(Name = "Is Buyer")]
public bool IsBuyer { get; set; }

在 Razor 页面中:

<div class="row g-my-4">
    <div class="col-md-10 g-pl-0">
        <div class="row">
            <div class="col-md-1">&nbsp;</div>
            <div class="col-md-7 g-pl-0 g-pr-0" id="IsBuyer">
                <label>
                @Html.CheckBoxFor(m=>m.IsBuyer)
                @*@Html.CheckBoxFor(model => model.IsBuyer, new { id = "CheckBuyer" })*@

                @*@Html.CheckBox("IsBuyer")*@
                Buyer
                </label>
            </div>
        </div>
    </div>
</div>

我尝试使用所有东西,但没有任何效果。

获取数据值以使用 ajax 调用

在这里您可以看到 IsBuyer 属性为 null = 空,而在服务器端它的值是错误的,但是我已经检查了每个复选框,但这就是我要返回的内容

【问题讨论】:

  • 试试$('IsBuyer').prop('checked') 而不是.val()。
  • 现在变成未定义的,而不是空的
  • 对不起,应该是$('#TheCheckBoxId')。忘了#
  • 是的,我知道这样"IsBuyer": $('#IsBuyer').prop('checked'), 所以它的结果是未定义的
  • 但我猜是关于 id,我应该在哪里提到复选框 id?

标签: asp.net asp.net-mvc asp.net-core checkbox


【解决方案1】:

尝试使用通常的BeginForm() 块并发布如下数据:

@model Models.ViewModel

@using (Html.BeginForm())
{
    <div class="form-group row">
        <p>@Html.LabelFor(l => Model.IsBuyer) </p>
        @Html.CheckBoxFor(r => Model.IsBuyer)
    </div>   

    <input id="Button" type="submit" value="Save" />
}

在控制器代码中:

public IActionResult IndexTest()
{
    var model = new ViewModel() { IsBuyer = true };
    return View(model);
}

[HttpPost]
public IActionResult IndexTest(ViewModel data)
{
    if (ModelState.IsValid)
    {
        // your code here...
    }            
    return RedirectToAction("IndexTest", data);
}

// View data model class
public class ViewModel
{
    [Display(Name = "Is Buyer")]
    public bool IsBuyer { get; set; }
    // Additional propereties is defined here...
}

【讨论】:

    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多