0

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?

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

This looks grate, I will try this and let you know if it works.
I have now tried this but can´t get it to work with the regular ASP MVC view engine? I have added this to the view : <%: Html.HiddenFor(c => c.L) %> and then I set the value with jquery like this : $('#L').val('1');. I can see that the L is set from 0 to 1 at the client, but when submitting the L is still 0?
Did you check the actual POST or what the value in MVC after the POST? In Google Chrome, you can see all HTTP traffic and what's actually posted.
I found the problem. In Content1(<asp:Content) I got the form with filters and in Content2 I got the list. I tried to place the javascript and the hidden field in Content2 but as this is not a part of the form in Content1 it will not be effected. Is it possible to place a form over several Content tags? Thanks for the help!!
1

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

1 Comment

Sorry, I was maby not clear. The problem is not to submit with javascript but to set a property on the object that will return to server when a submit is done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.