【问题标题】:how to send hidden field to controller via model binding如何通过模型绑定将隐藏字段发送到控制器
【发布时间】:2016-12-18 03:31:16
【问题描述】:

希望有人能帮助我,这可能是一个简单的问题,但让我很沮丧,因为没有解决办法,

我想通过模型绑定将值从隐藏字段传递给控制器​​, 无论我使用什么方法,只需通过模型将值从视图传递到控制器就可以为我工作,

这是我的滑块范围

<label for="amount">دامنه قیمت:</label>
<div id="connect" class="noUi-target noUi-ltr noUi-horizontal noUi-background">

</div>

这是隐藏字段,

<input type="hidden" name="MinPrice" value="@Model.MinPrice" id="MinPrice" />
<input type="hidden" name="MaxPrice" value="@Model.MaxPrice" id="MaxPrice" />

< script >
  var connectSlider = document.getElementById('connect');

noUiSlider.create(connectSlider, {
  start: [40000, 800000],
  connect: true,
  range: {
    'min': 0,
    'max': 2000000
  }
}); < /script>
        <script>
            var connectBar = document.createElement('div'),
                connectBase = connectSlider.querySelector('.noUi-base');

            / / Give the bar a class
for styling and add it to the slider.
connectBar.className += 'connect';
connectBase.appendChild(connectBar);

connectSlider.noUiSlider.on('update', function(values, handle, a, b, handlePositions) {

  var offset = handlePositions[handle];

  // Right offset is 100% - left offset
  if (handle === 1) {
    offset = 100 - offset;
  }

  // Pick left for the first handle, right for the second.
  connectBar.style[handle ? 'right' : 'left'] = offset + '%';
}); < /script>
        

        <script>


            var valueInput = document.getElementById('MinPrice'),
                valueSpan = document.getElementById('MaxPrice');

            / / When the slider value changes, update the input and span
connectSlider.noUiSlider.on('update', function(values, handle) {
  if (handle) {
    valueInput.value = values[handle];
  } else {
    valueSpan.innerHTML = values[handle];
  }
});

// When the input changes, set the slider value
valueInput.addEventListener('change', function() {
  connectSlider.noUiSlider.set([null, this.value]);
});


< /script>

这是我的填充隐藏字段的JS,这两个字段填充正确,但不要通过模型向控制器发送数据,

谢谢大家,

更新

这是我的模型:

 public class SearchModel
{
    public string Devision { get; set; }
    public string Gender { get; set; }
    public int? MinPrice { get; set; }
    public int? MaxPrice { get; set; }
    public string Brand { get; set; }
    public string Sport { get; set; }
    public string Size { get; set; }
    public string ProductGroup { get; set; }
    public List<tblSiteItem> Result { get; set; }
    public List<tblSiteItem> Sales { get; set; }
    public List<string> Devisions { get; set; }
    public List<string> Genders { get; set; }
    public List<string> Brands { get; set; }
    public List<string> Sports { get; set; }
    public List<string> Sizes { get; set; }
    public List<string> ProductGroups { get; set; }
    public List<tblSiteCart> CartItems { get; set; }
    public int PageNo { get; set; }
    public int Barcode { get; set; }
}

正如我所说,该值已正确填充,因此我不需要代码来纠正它,只是不要将 hdnValue 绑定到我模型中的字段。 我的意思是 MinPrice 和 MaxPrice。

已编辑 可悲的是,我不允许上传图片,如果我一切都很明显, 无论如何,我解释一下细节:

  1. 当我改变 slideBar 时,我的 JS 触发并且值改变,

  2. 当我点击搜索按钮时,我模型中的所有字段都是字段,除了这两个字段,我的意思是 MinPrice 和 MaxPrice

  3. 结果显示一个空白页面,我的 Js 再次被触发然后返回默认值,

在最后一次尝试中,我将隐藏字段更改为 type="text" 并看到当我更改滑动条时,值在我的文本框中,但在触摸搜索按钮时未绑定到我的视图模型。

我确定我的视图模型有问题,但我怎么能理解不正确的地方:(请查看我的代码

【问题讨论】:

    标签: javascript asp.net-mvc model-binding hidden-field nouislider


    【解决方案1】:

    您输入的名称不正确。您应该从中删除 Model. 部分。如果您使用HtmlHelper.HiddenFor,您将获得以下信息:

    <input type="hidden" name="MaxPrice" value="@Model.MaxPrice" id="MaxPrice" />
    

    这样,输入将正确地提交给您的模型。

    看看this answer

    【讨论】:

    • 它不起作用,我不知道是什么问题,你可以在我的模型中看到它们工作的其他字段,但是这个隐藏...
    • 我也用过这个:@Html.HiddenFor(m => m.MinPrice, new { id = "MinPrice", Value = @Model.MinPrice }) ,但它又没有填满 MinPrice与 hdnValue,
    • 这真的很奇怪。在提交表单之前,您确定这些值正在正确更新吗?
    • 明天请看我的cmets,我会更新我的帖子到底发生了什么,再次感谢
    • 请看一下我的更新,我真的厌倦了测试各种方法
    【解决方案2】:

    使用此代码获取值:

    var userRole = "";
    userRole = $("#hdnVal").val();
    alert(userRole);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="hidden" id="hdnVal" value="@Model.MinPrice" />

    【讨论】:

    • 在你的例子中你写了 你的值我希望是 Model.MinPrice,我希望看到我的模型在控制器中填充了这些数据
    • 试试这个:你可以用 value="@Model.MinPrice" 代替 value="YourValue"。
    • 我也测试过,但没有成功,请查看更新后的帖子,感谢您的时间我的朋友
    【解决方案3】:

    关注这个。

    在 .cshtml 页面上

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="hidden" id="hdnVal" value="@Model.MinPrice" /> <input type="button" name="Submit" value="Submit" id="btnSubmit" class="btn btn-primary" />

    Js

    var userRole = "";
    userRole = $("#hdnVal").val();
    alert(userRole);
    $('#btnSubmit').click(function() {
          var formData = new FormData();
          formData.append("userRole ", userRole);
          $.ajax({
            type: "POST",
            url: "/Controller/YourAction/",
            data: formData,
            dataType: 'json',
            contentType: false,
            processData: false,
            success: function(result) {
              if (result.Message == "success") {
                alert("Success");
              }
            }
          });
    
        }
    

    C# 代码

    public JsonResult YourAction()
    {
    string Role = Request.Form["userRole "];
    //You can get the value of role
    }
    

    【讨论】:

    • 请看更新的部分,我不需要在控制器中有一个 hdnField,而是一个有字段的模型必须用 hdnField 填充,model.Minprice=hdnValue
    【解决方案4】:

    我遇到了同样的问题,经过多次测试,我发现解决方案通过 ajax 发送值,但以字符串 JSON 格式构建请求的数据,其中隐藏字段不带单引号,其他字段带单引号.下面显示了示例。我希望这个变体对你有所帮助。

    向控制器发送数据的 JavaScript 代码

                $("#saveSearchModel").on("click", function (e) {
                    e.preventDefault();
                    // Variables for fields values
                    var devision = $("#Devision").val();
                    var gender = $("#Gender").val();
                    var minPrice = $("#MinPrice").val();
                    var maxPrice = $("#MaxPrice").val();
                    var brand = $("#Brand").val();
                    /*
                       Get the other fields...
                    */
                    // Data for pass to controller via ajax
                    var data1 = "{'Devision':'" + devision + "','Gender':'" + gender + "',MinPrice:" + minPrice + ",MaxPrice:" + maxPrice + ",'Brand':'" + brand + /*Add the other fields...*/ + "'}";
    
                    $.ajax({
                        url: '/Controller/Action1',
                        type: 'POST',
                        contentType: "application/json; charset=utf-8",
                        data: data1,
                        success: function (result) {
                            // Do something
                        }
                    });
                });
    

    控制器中用于接收数据的代码

                [HttpPost]
                public void Action1(SearchModel model)
                {
                    // Gets the values of model
                    string devision = model.Devision;
                    string gender = model.Gender;
                    int? minPrice = model.MinPrice;
                    int? maxPrice = model.MaxPrice;
                    string brand = model.Brand;
                    /*
                        Gets the others values of model...
                    */
                }
    

    【讨论】:

      猜你喜欢
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多