Search code examples
javascriptasp.netasp.net-mvcpostbackdopostback

Javascript onclick _dopostback in MVC not posting back


NET MVC to try to postback after confirmation using javascript, this is the button:

<input type="submit" id ="RemoveStatus" value="Remove Status" name="button" onclick="return CheckRemove();"/>

This is my javascript in my CheckRemove() js function:

var button1 = document.getElementById("RemoveStatus");

     if (confirm("Are you sure you want to remove status?") == true) 
                {
                    button1.disabled = true;
                    button1.value = "Removing status...";
                    __doPostBack('RemoveStatus', '');
                    return true;


                }
                else 
                {
                    return false;
                }

But for some reason I get an object expected error at the __doPostBack bit, I've clearly set the id, button1 gets populated too in debug, i'v tried passing button1.id and button1 too into the __doPostBack call but it wont postback and keeps saying object expected, any ideas?


Solution

  • You don't have the concept of postbacks in MVC like you had in webforms. Simply use nameoftheform.submit(); instead.

    http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml

    You can use the following to generate the id in the form tag:

    <% using (Html.BeginForm("Create", "Test", FormMethod.Post, new {id="myForm"})) {%>
    

    and in the script use:

    document.getElementById('myForm').submit();
    

    Personally I'm a fan of jQuery so that last one could be rewritten like:

    $('#myForm').submit();