我想调用可以在后台做某事的方法,但我不想更改当前视图。这是方法:
public ActionResult BayesTraining(string s,string path)
{
XmlParse xp = new XmlParse();
using (StreamWriter sw = System.IO.File.AppendText(path))
{
sw.WriteLine("d:/xml/"+xp.stripS(s)+".xml");
sw.Close();
}
return RedirectToAction("Index");
}
如您所见,我目前正在使用RedirecttoAction,该方法在方法完成后才重新加载页面。考虑到该方法不会影响UI,我不想每次使用它时都会刷新网页。它的工作应该在后台完成。那么,我怎么能称呼它,而无需重定向视图呢?
如果您想要一些东西,可以发射并忘记使用Ajax调用。例如,如果将操作方法更改为
public JsonResult BayesTraining(string s,string path)
{
XmlParse xp = new XmlParse();
using (StreamWriter sw = System.IO.File.AppendText(path))
{
sw.WriteLine("d:/xml/"+xp.stripS(s)+".xml");
sw.Close();
}
return Json("Success");
}
然后,在您的视图中,您需要通过jQuery绑定到UI事件,例如,绑定到带有ID的按钮,请执行以下
$("#BayesTraining").click(function(){
$.post('@Url.Action( "BayesTraining" , "ControllerNameHere" , new { s = "stringcontent", path="//thepath//tothe//xmlfile//here//} )', function(data) {
//swallow success here.
});
}
免责声明:未测试上述代码。
希望它会指向正确的方向。
如果该方法不影响UI,是否需要返回Action Result?它不能返回void吗?
public void BayesTraining(string s,string path)
{
XmlParse xp = new XmlParse();
using (StreamWriter sw = System.IO.File.AppendText(path))
{
sw.WriteLine("d:/xml/"+xp.stripS(s)+".xml");
sw.Close();
}
}