2012-10-22 42 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(); 
    } 


}