2012-08-02 73 views
1

我想打印存儲在控制器對象中的值。我試圖尋找答案,但我沒有找到正確的答案。請幫助如何在控件中打印值 - MVC3

//my code in control 

public ActionResult PrintOutput() 
     { 
       ModalClass myObject = new ModalClass    
       myObject.load(str); 
       ViewBag.myOject = myOject.ToString(); 
       return View("PositionPrint"); 
     } 




    //In view page I have created a **PartialView**. Inside partial view I 
    // have given below code alone 


     @Html.Raw(@ViewBag.myOject) 

回答

2

您不能使用object作爲變量名 - 它是語言的關鍵字。您的控制器通常會通過返回填充了來自視圖包或自定義模型的數據的視圖來「打印」值。如果你只需要打印一個原始的html字符串 - @Html.Raw(myObject)

在你的控制器操作中,艱難的,你需要把值放在某個地方,以便視圖可以訪問它。例如:

public ActionResult PrintOutput(sting str) 
{ 
    Modalclass myObject = new Modalclass(); 
    myObject.load(str); 

    ViewBag.myObject = myObject; //probably at least ToString() call is due here 
    return View(); 
} 

並在視圖使用@Html.Raw(@ViewBag.myObject)打印裏面有什麼。

P.S.但是你真的不應該嘗試打印出整個對象的內容。這是一個毫無意義的行爲。 (調試除外)具體。對象中的每個數據屬性都應該打印到視圖上的特定UI元素。

+0

感謝您的回覆! [ViewBag._ObjectPM = _ObjectPM;]我已經給出了我上面提到的代碼,並返回[返回視圖(「PositionPrint」,_ObjectPM);]和部分視圖頁[@ Html.Raw(@ ViewBag._Object)] ..但是沒有運氣。我覺得我缺少一些東西 – Muthukumar 2012-08-02 09:33:19

+0

對象是什麼。 Modal類的來源是什麼?在問題主體中提供更多關於問題的代碼,所以我們有一個材料inverstigate =) – 2012-08-02 12:17:16

+0

更新了我的完整代碼。按照您的要求。請幫助 – Muthukumar 2012-08-02 13:02:29

0

只要可能,儘量避免動態魔術變量,如ViewBagViewData。這些Magic變量讓你的代碼變得醜陋。 總是嘗試使用強類型

有一個ViewModel爲您的觀點。例如:如果您想打印有關客戶的詳細信息。您可以創建一個視圖模型(這只是一個POCO)對於這樣的

public class CustomerPrint 
{ 
    public string FirstName { set;get;} 
    public string JobTitle { set;get;} 
} 

現在在你的控制器動作,設置這個值,並傳遞到您的視圖。

public ActionResult PrintOutput() 
{ 
    var customerPrintVM=new CustomerPrint(); 
    customerPrintVM.FirstName="Jon"; 
    customerPrintVM.JobTitle="Developer"; 
    return View(customerPrintVM); 
} 

由於我們正在傳遞CustomerPrint類的對象,所以我們的視圖應該強類型化到這個類中。所以改變你的觀點。

@model CustomerPrint 

<h2>This is your view content</h2> 
<p>@Model.FirstName</p> 
<p>@Model.JobTitle</p> 
@Html.Raw(Model.FirstName) 

如果你的ViewModel類駐留在命名空間中,你可能需要給FULLPATH到類第一喜歡這樣

@model YourNameSpaceName.CustomerPrint 

您可以訪問這個格式模型的屬性Model.PropertyName(例如:Model.FirstName)和剃刀中,如果表達式不在代碼塊中,則需要使用@