Lyly
Lyly

Reputation: 726

MVC: How to call Javascript function in action?

In my view I has a function called testalert,and in my controller I has a action called Index,I use javascriptmodel can solve my problem,but I find that if my action do not return a view(),for example:just return Json(model),the javascriptmodel will not work.How to call js function when I return json?Why do the javascriptmodel only be designed to work well in return view?

function testalert(para) {
     alert(para);
    }

public ActionResult Index()
    {
  //work well  and alert "abc"   
 this.AddJavaScriptFunction("testalert", PageLoadEvent.Ready, null, "abc");
        return View();
    }
public ActionResult GetData()
    {
  var restult="data"; 
 // not work     
 this.AddJavaScriptFunction("testalert", PageLoadEvent.Ready, null, "abc");
   return Json(restult);
    }

Upvotes: 0

Views: 1287

Answers (1)

nilphilus
nilphilus

Reputation: 620

I've done f.e AsyncHelper.Call(url, params) which return as a result promise, and on clientside wait for promise.done and to my stuff.

shorter version:

var AsyncAction = (function () {
return {
    //options: passed to $.ajax       
    Call: function (options, helperOptions) {
        return $.ajax(options)
        .done(function (result) {
            helperOptions.onSucceed(result.model);
        });
    }
};

})();

Upvotes: 1

Related Questions