2012-10-22 44 views
0

我想调用将在后台执行某些操作的方法,但我不想更改当前视图。这是方法:从mvc4视图调用背景方法

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,我不想每次使用它时刷新网页。它的工作应该在后台完成。那么,我怎么称呼它,而不需要重定向视图呢?

回答

1

如果你想要的东西,你可以开火,忘记使用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事件,例如绑定到一个按钮BayesTraining的ID做以下

$("#BayesTraining").click(function(){ 
    $.post('@Url.Action("BayesTraining" , "ControllerNameHere" , new { s = "stringcontent", path="//thepath//tothe//xmlfile//here//})', function(data) { 
    //swallow success here. 
    }); 
} 

免责声明:以上代码未经测试。

希望它会指出你在正确的方向。

+0

对于FaF导弹+1;) – Vogel612

0

如果该方法不影响UI,是否需要返回ActionResult?难道它不是返回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(); 
    } 


}