0

バックグラウンドで何かを行うメソッドを呼び出したいのですが、現在のビューを変更したくありません。これは方法です:

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 に影響を与えないことを念頭に置いて、使用するたびに Web ページを更新したくありません。その仕事はバックグラウンドで行われるべきです。では、ビューをリダイレクトする必要なく、どのように呼び出すことができますか?

4

2 に答える 2

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.
   });
}

免責事項: 上記のコードはテストされていません。

うまくいけば、それはあなたを正しい方向に向けるでしょう。

于 2012-10-22T20:49:44.680 に答える
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();
    }


}
于 2012-10-22T20:56:33.190 に答える