views:

117

answers:

2

I am refactoring a web app built with previous versions of Asp.Net MVC where all the views have 2 codebehind files each.

Also if the views are working correctly I want to begin to remove all the code behind files as most of them are empty.

There are few of them that have properties like this in the codebehind:

public partial class List {
    public Message NewMessage { get { return new Message(); } }
}

Before completely removing them (I know this methods do not pertain to the views) how do I replicate them in the single page aspx or ascx?
I just tried to copy and paste the public methods in <% %> tags but this is not working.

+3  A: 

May I ask why you were using this approach in the first place? I think you could achieve the same thing by making your View strongly typed, and pass the message as the View's Model.

Inherits="System.Web.Mvc.View<Message>"

If you already have a strongly typed View, you could make a custom class in your class library that has room for your message, for example

public class ModelWithMessage  {
    public Message Message { get; set; }
    public Object Model { get; set; }
    public ModelWithMessage(Message Message, Object Model) {
        this.Message = Message;
        this.Model = Model;
    }
}

You can of course make that type generic as well, allowing for a ModelWithMessage<T> construct and avoiding having to cast the Model to whatever type you need.

Another way to do it would be to use TempData. In your Controller, set

TempData["Message"] = "Hello world!";

Then in your View you write the message out simply with

<%= TempData["Message"] %>

Which approach you choose depends on what your Message class contains.

Tomas Lycken
A: 

You've almost answered this for yourself there as you said 'I know this methods do not pertain to the views' :)

First I would move these methods out to the controller classes and pass any required data across in the Model (assuming that's an appropriate place for them), then when you have removed all the functionality from your code-behind files and have a clean separation again, you can go about removing the codebehind files from your views.

Steve Willcock