简体   繁体   中英

Send data from javascript to server

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?

  1. Add it as a hidden input (sample uses Razor view engine):

    @Html.HiddenFor(model => model.TheProperty)

  2. 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');
            }
        });
    });
});

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