Reputation: 2917
I feel really daft asking this, sure I'm missing something really simple, but I just can't get it to work!
I've created a ViewDataDictionary like this in the controller:
public ActionResult Index()
{
var recipient = new Recipient() {
FullName = "John Brown",
Company = "FP",
Email = "[email protected]"
};
ViewData = new ViewDataDictionary(recipient);
UserMailer.OnEventBook().Send();
return View();
}
But I can't work out how to access the data in the view.
I've tried:
@ViewData["FullName"]
@ViewData.recipient["FulName"]
@ViewData[recipient.FullName]
@Model.FullName
@recipient.FullName
...and a number of similar combinations. Can anybody point me in the right direction?
Update
I realise I could just pass it through using ViewBag or ViewData["recipient"]. But I'm curious about this way of doing it.
The below is from the docs for MvcMailer, and the guy who wrote it seems to know his stuff, so I figured it must be a valid way of passing data through.
var comment = new Comment {From = me, To = you, Message = "Great Work!"};
ViewData = new ViewDataDictionary(comment);
Update 2
Doh, I got it wrong.
The MvcMailer makes a call to an action within an action, and I should have been setting the ViewData in the sub action (OnEventBook() in the code above).
Upvotes: 0
Views: 81
Reputation: 1426
First change your controller code to:
var recipient = new Recipient() {
FullName = "John Brown",
Company = "FP",
Email = "[email protected]"
};
ViewData["Recipient"] = recipient;
Then in you view use the following code:
@((Recipient)ViewData["Recipient"]).FullName
Anyway if you want a to use a specific object to the View use a Strongly-typed view.
Update
If you still want to use ViewDataDictionary you should use the following code to access the model in your view:
@ViewData.Model.FullName
Upvotes: 3
Reputation: 747
you can transfer the recipient data as "Model" from the controller to the view
CONTROLLERS:
public ActionResult Index()
{
var recipient = new Recipient()
{
FullName = "John Brown",
Company = "FP",
Email = "[email protected]"
};
return view(recipient); //return the recipient as obj model
}
VIEWS:
@model YourNameSpace.YourRecipientModelFolder.Recipient
@{
ViewBag.Title = "Home Index";
}
<div>Model:</div>
<div>@Model.FullName</div>
<div>@Model.Company</div>
<div>@Model.Email</div>
Note: YourNameSpace.YourRecipientModelFolder.Recipient is something like this MyMVC.Models.Recipient
Upvotes: 2