Welcome to MSDN Blogs Sign in | Join | Help

Alex Yakhnin's Blog

Development and architecture for Windows Mobile devices. And a few useful tips on the way...

News

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).

 

Posted: Friday, October 10, 2008 4:02 PM by priozersk
Filed under:

Attachment(s): MVCDemoClient.zip

Comments

Fergara said:

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

# October 13, 2008 3:48 PM

FilipK said:

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.

# October 14, 2008 2:38 AM

priozersk said:

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.

# October 14, 2008 9:22 AM

Alex Yakhnin - Mobility Consultant, Former MVP said:

Last time I showed you how to create a simple Login Form and pass the data between the View and Controller

# October 14, 2008 6:50 PM

Fergara said:

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!

# October 16, 2008 9:19 AM

fox23 said:

AlexYakhnin在他的blog上发布了一系列关于WindowsMobileMVCFramework的文章.

# October 21, 2008 2:16 AM

Alberto Silva said:

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

# November 13, 2008 7:53 AM

eDGARDO PANCHANA said:

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)?

# August 2, 2009 8:44 PM

priozersk said:

The code and the sample posted on codeplex:

http://mobilemvc.codeplex.com

# August 9, 2009 11:33 AM
Anonymous comments are disabled
Page view tracker