I am building a ASP.NET MVC webapplication and have a 开发者_运维问答question:
Say that I have a strongly typed view, when hitting submit the object(of the strongly type) will be filled and sent to the server.
Now say that one of the properties of the strongly typed is not used in the form, instead I need to set this with javascript if the user press a button (not submit button).
How do I do this?
As I understand it, you want to assign a value to the property when a button is pressed?
Add it as a hidden input (sample uses Razor view engine):
@Html.HiddenFor(model => model.TheProperty)
Create a small jquery script:
<script type="text/javascript">
$('document').ready(function(){
// this is the id of the button that the user presses.
// It must have a "ID" attribute
$('#someButtonId').click(function() {
$('#TheProperty').val('Value to set');
});
});
});
</script>
You could use AJAX to send a request to the server with javascript. jQuery has great methods for doing so such as $.ajax
, $.post
, $.get
. Example:
$(function() {
$('#someButtonId').click(function() {
// when some button is clicked send an AJAX request:
$.ajax({
url: '/home/someaction',
data: { someField: 'some value to send' },
success: function(result) {
alert('value successfully sent to server');
}
});
});
});
精彩评论