Dharti Sojitra Dharti Sojitra - 3 months ago 11
Ajax Question

ajax call to controller method after formsubmit and getdata

i have One Method POST Startmailing() in controller
When I submit form on Button Click Startmailing()method start execution And Count in that method increases.

public void Startmailing()
{
for (int i = 0; i < 100; i++)
{
_count++;

}

}


What I want to do is After Form Submit I want to call Another Method GetCount() of that controller which returns Count

[HttpPost]
public ActionResult GetCount()
{
return Json(new { Data = _count });
}


But i Am facing Problem It Only Executes Getcount() method again and again And only returns 0.. How can I Execute Both Method And get Increased Count

i tried to call this method after
formsubmit()

Send



function submitform() {

var f = document.getElementsByTagName('form')[0];

f.submit();
showCount();
function showCount() {
$.ajax({
url: '@Url.Action("GetCount", "Test")',
type: "POST",
success: function (a) {
alert(a.Data);
}
});
setTimeout(showCount(), 1000);
}


Thanks In Advance !

Any help Will be Appreciated..
Edit Questions if Required..

Answer

While posting data settimer which get count from GetCount method after every 5s...I used thread.sleep just to hold for moment... In your case this is not required as mail sending itself takes time...

In controller

    public static long Count;

    [HttpPost]
    public JsonResult GetCount()
    {
        return Json(Count);
    }

    [HttpPost]
    public void Index(FormCollection data)
    {
        Count = 0;
        for (int i = 0; i < 10000; i++)
        {
            Thread.Sleep(1000);
            Count++;
        }
    }

Used this script

    <script>
    function btnSubmit() {
         window.setInterval(starttimer, 5000);

         var f = document.getElementsByTagName('form');
         f.submit();
    }

    function starttimer() {
        $.ajax({
            type: 'POST',
            url: "/SendMail/GetCount",
            dataType: 'json',
            asyn: false,
            timeout:5000,
            success: function (data) {
                $("#Count").val(data);
            }
        });
    }

</script>
Comments