1

Hope one kindly can help me, it may be a simple question but frustrated me as there is no fix for it,

I want to pass value from a hidden field to controller via model binding, no matter what approach I use, just passing the value from view to controller via model can work for me,

this is my slider range

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

</div>

this is the hidden field,

<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>

this is my JS that fill the hidden field, these two fields are filled correctly, but dont send data to controller via model,

thank you all pal,

Updated

this is my model:

 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; }
}

As I said the value is filled correctly so I do not need code to make it corrected, Just not bind the hdnValue to the field in my model. I mean MinPrice and MaxPrice.

Edited I am not allowed to upload images sadly, If I were everything was pretty obvious to look at, any way, I explain the detail:

  1. when I change the slideBar, my JS fires and values change,

  2. when I click the search button all the fields in my model is field except for these two field , I mean MinPrice and MaxPrice

  3. result shows an empty page , again my Js keep fired then come back to the default values,

in the last try I changed the hidden field to type="text" and saw that when I change the slidebar the value is in my text box but not binded to my view model when touch search button.

I am sure there is something wrong with my viewmodel, but How I can understand what is incorrect :( please kindly look at my code

sariiia
  • 71
  • 1
  • 1
  • 10

4 Answers4

0

Use this code for get the value:

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" />
  • in your example u wrote Your value I expect to be a Model.MinPrice, with that I expect to see my model is filled with this data in the controller – sariiia Aug 11 '16 at 13:35
  • **Try this:** Instead of value="YourValue" you can put value="@Model.MinPrice". – Manohar Mandal Aug 12 '16 at 05:59
  • I tested this too but no success, please review the updated post, thanks for your time my friend – sariiia Aug 12 '16 at 10:13
0

Follow this.

On .cshtml Page

<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# Code

public JsonResult YourAction()
{
string Role = Request.Form["userRole "];
//You can get the value of role
}
  • please look at the updated section, I do not need to have one hdnField in the controller, instead a model that has a field have to be filled with hdnField, model.Minprice=hdnValue – sariiia Aug 11 '16 at 13:27
0

The names of your inputs are incorrect. You should remove the Model. part from it. If you used HtmlHelper.HiddenFor, you'd get the following:

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

This way, the inputs will get submitted to your model correctly.

Have a look at this answer.

Community
  • 1
  • 1
Dygestor
  • 1,260
  • 1
  • 10
  • 20
  • it does not work, I do not know whats the problem, I have other field as you can see in my model that they work , but this hidden... – sariiia Aug 11 '16 at 14:30
  • I also had used this : @Html.HiddenFor(m => m.MinPrice, new { id = "MinPrice", Value = @Model.MinPrice }) , but it again des not fill MinPrice with the hdnValue, – sariiia Aug 11 '16 at 14:31
  • That is really strange.. Are you sure the values Are updating correctly, before you submit the form? – Dygestor Aug 11 '16 at 19:23
  • Please see my comments tomorrow, I will update my post what happen exactly , thanks again – sariiia Aug 11 '16 at 22:09
  • please kindly have a glance on my update, I am really fed up wit testing various approach – sariiia Aug 12 '16 at 10:16
0

I had the same problem and after several test I found the solution sending values via ajax but building the data for the request in a string JSON format, where the hidden fields, are written without single quotes and the other fields with single quotes. Below is shown the example. I hope that this variant help you.

JavaScript code to send data to controller

            $("#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
                    }
                });
            });

Code in controller to receive data

            [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...
                */
            }
Juan Carlos
  • 83
  • 1
  • 5