Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax.BeginForm with OnBegin prevent action to be called

I am using Ajax.Begin Form in my MVC 3 + Razor application

    using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions { OnBegin = "ValidateDateFunction('" + @abc.xyz + "')", HttpMethod = "POST", UpdateTargetId = "savebutton" }))
   {
         <input type="submit" value="Save" />
   }

Below is how my onBegin method looks like. I am passing a value to this method, I am able to get a proper alert.

    function ValidateDateFunction(id) {
        alert(id);
        if(some-ConditionUsing-formId)
        {
            return false;
        }

        return true;           
    }

Now using this I wanted that if my condition fails then action should not be called. But here in my case in both condition my action is called.

Please help on this.

Below is my actual validate method

        function ValidateDateFunction(fId) {

        var first = document.getElementById("startDate" + fId);
        var second = document.getElementById("endDate" + fId);

        if (first.value == "" && second.value != "") {
            alert("Please select both dates");
            return false;
        }
        else if (first.value != "" && second.value == "") {
            alert("Please select both dates");
            return false;
        }

        var startDateVal = new Date(first.value);
        var endDateVal = new Date(second.value);

        if (startDateVal.getTime() > endDateVal.getTime()) {
            alert("Error ! The start date is after the end date!");
            return false;
        }
        alert('should not reach here');
        return true;

    }
like image 919
Yasser Shaikh Avatar asked Apr 05 '12 07:04

Yasser Shaikh


People also ask

What does Ajax BeginForm do?

Ajax. BeginForm is the extension method of the ASP.NET MVC Ajax helper class, which is used to submit form data to the server without whole page postback.

What is the difference between Ajax BeginForm and Html BeginForm?

BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax. BeginForm() creates a form that submits its values using an asynchronous ajax request.

What is the purpose of UpdatetargetId when specifying an Ajax form?

UpdatetargetId is the id of the DOM element which you want to update depending upon repsonse from the server. If you are returning any View or PartialView from controller using Ajax. BeginForm . This DOM element will be updated and will have view content you have returned.


1 Answers

found it !

just had to tweak my OnBegin property to

OnBegin = "return ValidateDateFunction('" + @abc.xyz + "')"

Links I referred ASP.Net MVC 3.0 Ajax.ActionLink Onbegin Function true the execute the action?

like image 54
Yasser Shaikh Avatar answered Sep 27 '22 17:09

Yasser Shaikh