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?

DarthVader
  • 52,984
  • 76
  • 209
  • 300

3 Answers3

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).

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
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);
        }
    });
});
coffeeyesplease
  • 1,018
  • 9
  • 15
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

Community
  • 1
  • 1
Betty
  • 9,109
  • 2
  • 34
  • 48