Search code examples
javascriptc#asp.net-mvc-5http-postasp.net-mvc-views

Get a value set via Javascript in a HTTP Post function


I am coding a MVC5 internet application and would like to know how to set a value in Javascript in a View that can be retrieved in the View's HTTP Post method.

I have tried this View code:

<input type="hidden" id="testHiddenField" value="test" />

With this Javascript code:

$("#testHiddenField").val("test value set");

However, in the HTTP Post method, I am not sure how to retrieve this value.

If the above code is not correct, what is the best way to retrieve a value that is set via Javascript in a MVC View in the HTTP Post function for the View?

Thanks in advance.


Solution

  • you can try to recover the value at the click of the button submit, or if that 'testHiddenField' is defined in your model , you need to put the name attribute of input , example :

    assuming your property in the model is called the 'testHiddenField'

    public String testHiddenField;
    

    when recovered in the post, not forget to put the name in the attribute

    <input type="hidden" id="testHiddenField" value="test" name="testHiddenField"/>
    

    to be recognized in your model, If not set the model . There will be recognized

    another solution is Razor:

    @Html.HiddenFor(input => input.testHiddenField, new {@value="test"})
    

    or click of your button submit of form:

    <button type="submit" id="btn" value="POST">
    <script>
       $('#btn').click(function(){
        $('#testHiddenField').val();
    });
    </script>