tags:

views:

35

answers:

1

Instead of:

public ActionResult Index()
{
    ViewData["foo"] = _repository.GetFoos().ToList();
    ViewData["bar"] = new string[] { "blah" };
    ViewData["baz"] = "";
    return View();
}

and then:

public ActionResult Index(string baz)
{
    // Do stuff...

    ViewData["foo"] = _repository.GetFoos().ToList();
    ViewData["bar"] = new string[] { "blah" };
    ViewData["baz"] = baz;
    return View();
}

I was thinking about ways to reduce typo errors by making the ViewData a little more structured, without having to add (yet) another ViewModel class. I came up with the following:

public ActionResult Index()
{
    var foo = _repository.GetFoos().ToList();
    var bar = new string[] { "blah" };
    var baz = null;

    ViewData = new ViewDataDictionary {
        {"foo", foo},
        {"bar", bar},
        {"baz", baz }
    };

    return View();
}

public ActionResult Index(string baz)
{
    var foo = _repository.GetFoos().ToList();
    var bar = new string[] { "blah" };
    var baz = null;

    // Do Stuff...

    ViewData = new ViewDataDictionary {
        {"foo", foo},
        {"bar", bar},
        {"baz", baz}
    };

    return View();
}

Is it a bad idea to overwrite the ViewData like that? I'm pretty sure this wouldn't cause problems with RenderPartials, but would I no longer be able to call RenderAction in a view?

+1  A: 

Is it a bad idea to overwrite the ViewData like that?

No. It is not bad idea. But this is not common.

I'm pretty sure this wouldn't cause problems with RenderPartials, but would I no longer be able to call RenderAction in a view?

You should be ok with all that.

But have a llok at your code without overwriting the ViewData and after.

You did not eliminate any typo error. You have the same number of magic strings in both cases.

So I would still recommend to add a ViewModel. For simplicity's sake just define your ViewModel within the controller class so you'll have it all in one place.

Dmytrii Nagirniak
Hmm, that gives me another (probably crazy) idea. I could set the controller as the model and use it's public instance variables in the view. Which would be very rails-like.
wm_eddie
Actually, I'm really liking the way return View(this) feels...
wm_eddie
Hmm, that is another option. I don't think it is too bad to do that. But it does violate SRP.
Dmytrii Nagirniak