2017-06-04 65 views
0

我有一個名爲AspNetAssessment_QuestionController通過調用它的方法返回從方法的觀點

public ActionResult Excel_Data(HttpPostedFileBase excelfile) 
{ 
    if (excelfile == null) 
    { 
     ViewBag.Error = "Please select an excel file"; 
     return View("Create"); 
    } 
    else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx")) 
    { 
     return View("Index"); 
    } 
    else 
    { 
     ViewBag.Error = "File type is incorrect"; 
     return View("Create"); 
    }   
} 

控制器的方法現在,當這個方法返回的視圖中,請求的視圖需要一些viewbag數據來運行其剃刀語法,就像在「創建」和「索引」都有:

@Html.DropDownList("ClassID", null, htmlAttributes: new { @class = "form-control" }) 

由於該系統只返回我的看法沒有擊中它不能從創建和索引的方法獲取viewbag的值的方法。

我還添加了路由,以便他們打他們的方法routes.config文件

routes.MapRoute(
       name: "AspNetAssessment_Question/Create", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "AspNetAssessment_Question", action = "Create", id = UrlParameter.Optional } 
      ); 

,並同樣適用於指數,但是當excel_data方法返回查看我收到一個錯誤Viewbag.propertyname數據丟失的以下網址

http://localhost:1331/AspNetAssessment_Question/Excel_Data 

我甚至試着撥打自己的方法,如創建(),而不是返回視圖(「創建」),但它失敗了,並沒有渲染視圖。

創建方法有兩種形式。一個命中Excel_data和另一個調用創建方法的方法創建方法

我該如何擊中他們的方法並從Excel_Data中返回視圖,以便他們從Excel_Data中獲取viewbag數據以及它們的方法和Excel_Data。

excel_data方法分配viewbag.Error和在創建的方法我有viewbag.ClassID和更多。

+1

你有沒有考慮使用partialviews的? – Gino

回答

1

解決你的問題很簡單

給予解決方案之前,我們需要了解兩件事情查看和redirecttoaction及其區別:

簡而言之,返回view()就像asp.net中的server.Transfer(),而redirecttoaction會將302請求發送到瀏覽器。

詳細信息可以在這個非常不錯的文章中找到:http://www.dotnettricks.com/learn/mvc/return-view-vs-return-redirecttoaction-vs-return-redirect-vs-return-redirecttoroute

所以現在解決問題的方法是:

用於返回,而不是返回查看()redirectoaction()

您的示例略有修改:

public ActionResult Excel_Data(HttpPostedFileBase excelfile) 
     { 
      if (excelfile == null) 
      { 
       ViewBag.Error = "Please select an excel file"; 
       return View("Create"); 
      }else if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx")) 
      { 
       return View("Index"); 
      } 
      else 
      { 


     TempData["Error"] = "File type is incorrect"; //replaced tempdata with viewbag 

       return RedirectToAction("Create","AspNetAssessment_QuestionController") 
      } 

     } 

注意:要保留的錯誤消息,請使用tempdata [「error」]而不是viewbag。上述代碼中提到的錯誤

你也可以直接訪問視圖創建類似下面而不做任何的創建操作方法到TempData的數據。

創建視圖代碼例如:

@if(tempdata["error"]!= null) 
{ 
    var result = tempdata["error"]; 
} 

完蛋了

FYI:

,如果你想怎麼樣投之間的不同TempData的對象和區別的其他信息viewbag,可視數據,TempData的,請參考以下鏈接:http://www.binaryintellect.net/articles/36941654-8bd4-4535-9226-ddf47841892f.aspx

那篇文章有一個很好的解釋

希望它是將有用

感謝 KARTHIK

+0

我批准使用tempdata'的'在會議/餅乾,我在我的答案用的。幹得好先生! –

+0

謝謝先生。快樂分享 –

0

如果只顯示要顯示的錯誤消息,則可以將它們保存到會話/ cookie,並使用RedirectToAction return RedirectToAction("Create", "AspNetAssessment_QuestionController");而不是return View("Create");

然後在創建/索引ActionResults,您可以添加這樣的事情:

public ActionResult Create() 
{ 
    ViewBag.Error = Session["ErrorMessage"].ToString(); 
    return View(); 
}