Reputation: 9589
I wanted to print values which I am storing in object on the controller. I tried searching for the answer but I didn't find proper answer. Please help
//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)
Upvotes: 1
Views: 2043
Reputation: 218862
Whenver possible, try to Avoid Dynamic Magic Variable like ViewBag
and ViewData
. These Magic variables makes your code ugly. Always try to use strong types.
Have a ViewModel
for your view. Ex : If you want to print the details about the Customer. You can create a ViewModel ( it is just a POCO) for that like this
public class CustomerPrint
{
public string FirstName { set;get;}
public string JobTitle { set;get;}
}
Now in your Controller action, set the values of this and pass that to your view.
public ActionResult PrintOutput()
{
var customerPrintVM=new CustomerPrint();
customerPrintVM.FirstName="Jon";
customerPrintVM.JobTitle="Developer";
return View(customerPrintVM);
}
Since we are passing the object of CustomerPrint class, Our view should be strongly typed to this class. So change your view like this.
@model CustomerPrint
<h2>This is your view content</h2>
<p>@Model.FirstName</p>
<p>@Model.JobTitle</p>
@Html.Raw(Model.FirstName)
If your ViewModel class resides in a namespace,you may need to give the fullpath to the class in the first like like this
@model YourNameSpaceName.CustomerPrint
You can access the Properties of your Model in this Format Model.PropertyName
(Ex : Model.FirstName
) and in razor, you need to use @
if the expression is not already inside a codeblock.
Upvotes: 0
Reputation: 10509
You can't use object as a variable name - it's a keyword of the language. Your controller usually "prints out" values by returning a view that is populated with the data from the view bag or custom model. If you just need to print a raw html string - @Html.Raw(myObject)
In your controller action, tough, you need to put the value somewhere so the view can access it. For example:
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();
}
And in the view use @Html.Raw(@ViewBag.myObject)
to print what's in it.
P.S. But you really should never try to print out a contents of an entire object. That is a rather meaningless act. (except for debugging) Be specific. Each data property in you object should be printed to a specific ui elements on the view.
Upvotes: 2