0

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.

Simon
  • 7,991
  • 21
  • 83
  • 163
  • 2
    Your hidden input needs a `name` attribute in order to post back a value. –  Feb 12 '15 at 11:22

2 Answers2

0

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>
Erick Wendel
  • 402
  • 6
  • 14
0

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.