简体   繁体   中英

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.

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>

the simple way is to do so:

1- in your html code.

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

notice I added name attribute to your code. do what you did in javascript the same way

2- in mvc action do some thing like this by adding testHiddenField as parameter to your action this will make mvc do what we called model binder

[HttpPost]
public ActionResult YourAction (string testHiddenField){
// break point here you will find your value is bind to what you set in javascript to view
}

if there is any problem contact me Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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