3
@using(Html.BeginForm("About", "User", FormMethod.Post , new { id="aboutme"}))
{
    <fieldset>
          <ul>
            <li> <label class="block">About me</label> @Html.TextAreaFor(m=>m.About.AboutMe)</li>
            <li> <input type="button" id="submit" class="input-button" /> </li>
          </ul>
    </fieldset>
}

<script type="text/javascript">
    $(function () {
        $('#submit').click(function () {

            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    // The AJAX call succeeded and the server returned a JSON
                    // with a property "s" => we can use this property
                    // and set the html of the target div
                    alert(result.s);
                    $('#ShowResultHere').html(result.s);
                }
            });
            // it is important to return false in order to
            // cancel the default submission of the form
            // and perform the AJAX call
            return false;
        });
    }); 
</script>

When i debug this, action URL becoming /User/undefined.

How can i fix it?

3 Answers 3

4

The this keyword refers to the source of the event, which is the submit button in this case. You want the form, so try this (using JQuery traversing):

url: $(this).closest("form").prop("action"),
type: $(this).closest("form").prop("method"),
data: $(this).closest("form").serialize()

The alternative would be to use <input type='submit' class='input-button' /> instead of the button, and listen for the event $("#aboutme").submit (that way this would actually refer to the form, as your code assumes).

Sign up to request clarification or add additional context in comments.

Comments

1

As an alternative attr function, to get the value of the attribute http://api.jquery.com/attr/ and also, jQuery has a shorthand for ajax post, $.post http://api.jquery.com/jQuery.post/ so your code could end like this

$("#submit").click(function(event){
    event.preventDefault();
    $.post($("#aboutme").attr("action"), $("#aboutme").serialize(), function (data) {
        if (data != null) {
            alert(result.s);
            $('#ShowResultHere').html(result.s);
        }
    });
});

Comments

0

Alternatively you could use the Ajax.BeginForm method instead, which lets you set a update target for any html returned.

Example: Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Comments

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.