Share via


Mobile MVC framework (part 1)

In order to show you the Mobile MVC framework I came up with, let me walk you through the same excersise we did when I showed you the MVC pattern. Let's create a simple application with the same login form. Let's create a Smart Devices project and rename the Form1.cs to LoginForm.cs and add a few controls to the form:

We will add the reference to the System.Mobile.Mvc assembly and start with the Controller.

Login Controller

Let's add the LoginController class and derive it from the Controller which is defined in the System.Mobile.Mvc. We will also define the constructor that excepts IView as a parameter and overrige OnViewStateChange method:

public class LoginController : Controller

{

     public LoginController(IView view)

            : base(view)

     {

     }

     /// <summary>

     /// This method indicates that something has been changed in the view.

     /// </summary>

     /// <param name="key">The string key to identify what has been changed.</param>

     protected override void OnViewStateChanged(string key)

     {

         base.OnViewStateChanged(key);

     }

}

Next, let's modify the OnViewStateChanged to handle the Login event from the view:

protected override void OnViewStateChanged(string key)

{

// Check what's changed

if (key == "Login")

{

// The values are in the ViewData. Let's validate them and return the status to the view

if (view.ViewData["UserId"].ToString() == "Alex" && view.ViewData["Password"].ToString() == "password")

{

// Pass the status to the view

this.view.ViewData["Status"] = "Login succedded.";

}

else

{

// Pass the status to the view

this.view.ViewData["Status"] = "Login failed.";

}

// Notify the view of the changes to the status

this.view.UpdateView("Status");

}

if (key == "Exit")

{

Application.Exit();

}

}

LoginView

Switch to the code view of your LoginView form and change it to derive from ViewForm. Let's also implement some logic for the menuLogin_Click and menuExit_Click event handlers:

public partial class LoginForm : ViewForm

{

        public LoginForm()

        {

            InitializeComponent();

        }

        private void menuLogin_Click(object sender, EventArgs e)

        {

            // Assign the values

            this.ViewData["UserId"] = txtUser.Text;

            this.ViewData["Password"] = txtPassword.Text;

            // Notify the Controller

            this.OnViewStateChanged("Login");

        }

        private void menuExit_Click(object sender, EventArgs e)

        {

            // Notify the Controller

            this.OnViewStateChanged("Exit");

        }

    

}

In the code for menuLogin_Click method we assign the values from the text boxes to the ViewData and make a call to the OnViewStateChanged to notify the controller of the event. Don't forget to pass the key which is used to recoginize what kind of event has happenned in the view.

All what is left here is to add an override for the OnUpdateView method to the LoginView which will be called when controller wants us to update the view:

protected override void OnUpdateView(string key)

{

      // Controller requested to update the view

      if (key == "Status")

      {

       // Update status label

           this.lblStatus.Text = this.ViewData["Status"].ToString();

      }

}

The last step is to wire up the controller and view together. You can do it by modifying the Main in the Program.cs:

[MTAThread]

static void Main()

{

     LoginForm form = new LoginForm();

      LoginController controller = new LoginController(form);

      Application.Run(form);

}

That is all to the code sample for now. I think the adavantages over the previous implementation are obvious - a lot less of the code to write. Plus we get a certain structure in the way the data is being passed between the view and controller. You can download the demo project from here. I am looking forward to any feedback on the approach I've taken.

 In the next posts I am going to show you how to pass strongly typed data between the layers (although, you should be able to guess it by looking at the MVC for ASP.NET).

 

MVCDemoClient.zip

Comments

  • Anonymous
    October 13, 2008
    Alex everything works fine but when the LoginForm (design) is openned, we cannot actually see the form because of the abstract class ViewForm. Is there a way to overcome through this? Thanks, Fergara

  • Anonymous
    October 13, 2008
    I understand that there's a lot less code to write (mainly the concrete IView interfaces), but I really don't like the string-based key approach. It's vulnerable to typos and can't be checked during compile time. I'd prefer to write rather more code than to use this string-based approach. But that's only my opinion :) BTW I wrote you an email few weeks ago about implementing some mean of navigation among controllers/views. Would you cover this topic in this new MVC series too, please? 2Fergara: try to comment out the Form class declaration like "public partial class LoginForm : /View/Form" when you need to use the designer.

  • Anonymous
    October 14, 2008
    I agree about string based approach, but as you said it's a choice between writing a lot more code or this approach. IMO, this can be mitigated by the ability to easilty write Unit Test against all layers. To Fergara: I've removed the abstract from ViewForm to allow to design the form in the later build.

  • Anonymous
    October 14, 2008
    Last time I showed you how to create a simple Login Form and pass the data between the View and Controller

  • Anonymous
    October 16, 2008
    2 FilipK: Thanks but yes, that´s what I´ve been doing to make the form appears to me. 2 priozersk: Thanks! It´s more productive being able to see the form right away!

  • Anonymous
    October 20, 2008
    AlexYakhnin在他的blog上发布了一系列关于WindowsMobileMVCFramework的文章.

  • Anonymous
    November 12, 2008
    Nestas coisas das teorias sobre a melhor forma de separar as diferentes camadas de uma aplicação, há

  • Anonymous
    August 02, 2009
    Hi my name is Edgardo Panchana, i am from Manta Ecuador, i have a question: where can i find some documentation about your DLL (System.Mobile.Mvc)?

  • Anonymous
    August 09, 2009
    The code and the sample posted on codeplex: http://mobilemvc.codeplex.com

  • Anonymous
    November 19, 2010
    I had downloaded this sample app. Its works fine, but when I navigate back from search form to login form. and  again went to searchForm, then unable to go back .... I have one more Doubt If I use this framework, and I am working on WareHouseMangement application, then there will be minimum 25 forms and one form may have multiple panels, As my observation we are keeping all forms in memory, will this handle by  framework. Thanks  it is saving lot of time for development, as now I dont have to worry about differeant screen size devices, as i just need to create different view for it   Thanks Abhijeet S

  • Anonymous
    January 23, 2011
    priozerks.. how can I remove tha abstract? :s