开发者

Send data from javascript to server

开发者 https://www.devze.com 2023-02-04 06:50 出处:网络
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

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

精彩评论

暂无评论...
验证码 换一张
取 消