0

我想在視圖中創建圖表,內容(名稱/系列/類型等)將全部由用戶在視圖中選擇的控件確定。從模型創建圖表。 (微軟圖表控件在asp.net mvc3)

只要我打開一個已經創建的圖表一切都很好,例如:

在我的視野:

 <controls above my graph> 

    <img src="@Url.Action("StatusGraph")"/> 

    <controls below my graph> 

控制器

//Creates status graph as specified by the controls in parent partial view or using   defaults 
    public ActionResult StatusGraph(){ 
     return View(); 
    } 

最後的StatusGraph視圖內:(以通用圖表this microsoft tutorial爲例)

@{ 
// TODO: use the data from the model to draw a chart 

var myChart = new Chart(width: 600, height: 400) 
    .AddTitle("Chart title") 
    .AddSeries(
     name: "Employee", 
     xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" }, 
     yValues: new[] { "2", "6", "4", "5", "3" }) 
    .Write(); 
    } 

正如我所說,這完美的作品,實際上在父視圖內顯示圖表,而不是在其自己的單獨窗口(真正的微軟,爲什麼?),然而,只要我試圖擴展StatusGraph方法接受參數圖表標題開始)並將其傳遞給StatusGraph當瀏覽器嘗試加載圖片時,出現404錯誤。

當我在擴展的StatusGraph方法中設置斷點時,我嘗試將標題傳遞給視圖,代碼從不停止,就好像它從不調用。

我的問題是:我該如何做這項工作?如何將數據從視圖傳遞到另一個視圖。

謝謝!

回答

1

你可以/應該使用視圖模型:

public class MyViewModel 
{ 
    public string Title { get; set; } 
} 

然後:

public ActionResult StatusGraph(MyViewModel model) 
{ 
    return View(model); 
} 

最後:

@model MyViewModel 
@{ 
    var myChart = new Chart(width: 600, height: 400) 
     .AddTitle(Model.Title) 
     .AddSeries(
      name: "Employee", 
      xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" }, 
      yValues: new[] { "2", "6", "4", "5", "3" }) 
     .Write(); 
} 

和繪製圖表傳遞值時:

<img src="@Url.Action("StatusGraph", new { title = "Chart title" })"/> 

當然的價值也可以在你的控制器動作來定義將它們作爲參數傳遞給img來源,而不是:

public ActionResult StatusGraph() 
{ 
    var model = new MyViewModel 
    { 
     // TODO: could come from a database or something 
     Title = "Chart title" 
    }; 
    return View(model); 
} 
+0

謝謝,我會嘗試,但爲什麼不將其與Viewbag工作? – Nieszka 2012-08-15 08:37:49

+1

Coz ViewBag很糟糕:-)我從來不會使用它,並且永遠不會建議對等開發人員使用它。 – 2012-08-15 08:38:01

+0

Aaaah!謝謝你,謝謝你,謝謝你!有用!自昨天晚上以來,我一直在爲這一小塊****而苦苦掙扎,而且從來沒有想過這是因爲我使用了ViewBag! (我傾向於這樣做測試某些事情,我懶得去寫出一個模型) 再次,非常感謝你! – Nieszka 2012-08-15 08:45:18