2

I'm pretty new to MVC, ASP.net, and, well, server-side scripting in general.

I was watching a tutorial video at www.asp.net/mvc where the person was explaining a template. He explained that the controller using viewdata to send information to the view.

Correct me if I'm wrong, but I believe it was used like this:

CONTROLLER: ViewData["PropertyName"] = value;

VIEW: <p><%= ViewData["PropertyName"] %></p>

Is this correct use?

What would be a better way to do it, instead of using ViewData, and what's bad about it?

bzlm
  • 9,626
  • 6
  • 65
  • 92
DarkLightA
  • 14,980
  • 18
  • 49
  • 57
  • You should really stick to a single question per post. I would move the "How is Html.Encode() used" question to a separate question since it's unrelated to the original. – Justin Niessner Jan 10 '11 at 18:05

4 Answers4

3

There are very view situations that I would advocate the use of the ViewData collection for.

For the most part, I would use Strongly Typed Views with individual View Models for each View.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

Rather than using the ViewData a better approach would be to create a new Model object and pass that to the View which is strongly typed to the Model.

Model (Models/MyModels.cs)

public class MyModel
{
    public string PropertyName { get; set; }
}

View (View/My/Index.aspx)

<%@ Page Language="C#" Inherits="ViewPage<MyModel>" %>
<p><%=Model.PropertyName %></p>

Controller (Controllers/MyController.cs)

public class MyController : Controller
{
    public ActionResult Index()
    {
        MyModel model = new MyModel()
        {
            PropertyName = "My Property Name"
        };

        return View(model);
    }
}

Html.Encode can be used like this:

<%=Html.Encode(someObject) %>

or this if you're using ASP.NET 4.0

<%: someObject %>
hunter
  • 62,308
  • 19
  • 113
  • 113
1

Justin is correct regarding ViewData usage, as well as using View Models (This is definitely the solution that will probably most fit your needs).

The Session is another option, but it can tend to be a slippery slope, but you did ask for alternatives.

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

ViewData is good for complete random data that you're not sure what you're going to need.

If you're constructing well-defined views you'll want to use Strongly Typed Views. These let your view inherit from a particular business object (or, more usefully, a ViewModel) to display the data. In this situation, instead of ViewData["SomeProperty"] you could have access to a strongly-typed Model member ie Model.SomeProperty.

Also, Html.Encode is meant to be put around data elements that repeat user-entered data. It is meant to prevent HTML injection.

Erik Noren
  • 4,279
  • 1
  • 23
  • 29