Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Sunday, 4 November 2018

What are MVP and MVC and what is the difference?

Let me provide  difference between MVP and MVC ,

Model-View-Presenter

If we are talking about In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.
MVP tends to be a very natural pattern for achieving separated presentation in Web Forms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.

Two primary variations

Passive View: The View is as dumb as possible and contains almost zero logic. The Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead the View exposes setter properties which the Presenter uses to set the data. All state is managed in the Presenter and not the View.
  • Pro: maximum testability surface; clean separation of the View and Model
  • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
  • Pro: by leveraging databinding the amount of code is reduced.
  • Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.

Model-View-Controller

In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:
    Action in the View
        -> Call to Controller
        -> Controller Logic
        -> Controller returns the View.
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.

Presentation Model

One other pattern to look at is the Presentation Model pattern. In this pattern there is no Presenter. Instead the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model, and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behaviour for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.

Saturday, 5 September 2015

Data Reader object to List type model Convert

How we can convert Data Reader object to List type model?
Most of developer are struggling while connecting with the DB, how to iterate those table data!
Developer may be go with DataTable fill using adapter concept, or it may be generic list concept.


I'm giving here pretty simple example for Mapping list.
 public static class Utility
    {
        public static List<T> DataReaderMappingToList<T>(IDataReader dr)
        {
            List<T> list = new List<T>();
            T obj = default(T);
            while (dr.Read())
            {
                obj = Activator.CreateInstance<T>();
                foreach (PropertyInfo prop in obj.GetType().GetProperties())
                {
                    if (!object.Equals(dr[prop.Name], DBNull.Value))
                    {
                        prop.SetValue(obj, dr[prop.Name], null);
                    }
                }
                list.Add(obj);
            }
            return list;
        }
    }

How we can access it?
// We are just passing command and iterating those kind of list.

 using (IDataReader dataReader = cmd.ExecuteReader())
                    {
                        stateDropdownAttribute = Utility.DataReaderMappingToList<StateDropdownAttribute>(dataReader);
                    }  

It's  pretty simple in this way to iterate it.

Thanks,
Gauttam

Monday, 23 March 2015

List of Model Object Post to Controller in ASP.NET MVC

Introduction

Several times, we want to post list of model object from view to controller while HttpPost. Many developers try to get the list of data through an array. But I'll tell you without using array also, we can get those list of model objects in a simpler way. Let's go step by step. Create an ASP.NET MVC 4 application. First, create two model classes, for example, EmployeeModelClass.cs and DepartmentModelClass.cs inside Model folder in solution.

Model


public class EmployeeModelClass
    {
        public string Name { get; set; }

        public string Address { get; set; }

        public string Contact { get; set; }

        public IEnumerable<DepartmentModelClass> DeptList { get; set; }                 
    }

public class DepartmentModelClass
    {
        public string DepartmentCode { get; set; }
        public string DepartmentName { get; set; }
    }  

Controller
public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            return View(new EmployeeModelClass());
        }

        [HttpPost]
        public ActionResult Index(EmployeeModelClass emp, IEnumerable<DepartmentModelClass> dept)
        {
            emp.DeptList = dept;
            return View(emp);
        }
    }

View

Here, I want to get Employee details with list of department names which belong to that employee. The business logic is multiple departments should assign to a single employee.
I hope you understood what I am trying to do here. See the controller. In HttpPost Action, I am not using any array to get the Department list from view page while HttpPost. Simply, I am passing two parameters inHttpPost like below:
[HttpPost]
        public ActionResult Index(EmployeeModelClass emp, IEnumerable<DepartmentModelClass> dept)
        {
            emp.DeptList = dept;
            return View(emp);
        }
See those parameters, EmployeeModelClass emp and IEnumerable<DepartmentModelClass> dept. We can get the employee data from emp object and list of department data from dept object very easily here.
See the view section inside for loop I am putting DepartmentCode and Departmentname four times. This property name should be the same as the property in Model object.
To see the result in output, append the following lines in view page:
@{
                    if (Model.Name != null)
                    {
                        <div>
                    
                            Employee Name : @Model.Name <br/>
                            Address : @Model.Address <br/>
                            Contact : @Model.Contact <br/>
                            
                            @{
                                if (Model.DeptList != null)
                                {
                                  <table>
                                        <tr>
                                            <th>Dept code</th>
                                            <th>Dept Name</th>
                                        </tr>
                                    
                                    @{
                                        foreach (var dept in Model.DeptList)
                                        {
                                            <tr>
                                                <td>@dept.DepartmentCode</td>
                                                <td>@dept.DepartmentName</td>
                                            </tr>
                                        }
                                    }
                                </table>
                            }
                            }

                        </div>
                    }
                }



Attached Code Link to Download Source


Sunday, 14 September 2014

MULTIPLE VIEWMODELS IN A SINGLE MVC VIEW

This post shows how to use multiple models in a single view. The models can be used in separated forms or together in one form. You could use each child model with a separate ajax post if required. Only properties in the parent class affect the child models, but a property in a child model does not effect the Model State of the other child models. In this way multiple models can be used and also validation for each model.

How the ViewModels are implemented:
The parent model class contains all child classes. Each class is another reusable model. In this way, the validation and ModelState can be used.
namespace MultipleModelsDemo.ViewModels
{
    public class IndexViewModel
    {
        public string HeaderText { get; set; }
 
        public TestOneModel TestOne { get; set; }
 
        public TestTwoModel TestTwo { get; set; }
    }
}

A child model used for the first form.
1
2
3
4
5
6
7
8
9
10
11
12
13
using System.ComponentModel.DataAnnotations;
 
namespace MultipleModelsDemo.ViewModels
{
    public class TestOneModel
    {
        [Required]
        public string PropertyOne { get; set; }
 
        [Required]
        public string PropertyTwo { get; set; }
    }
}
A second child model used for the second form.
1
2
3
4
5
6
7
8
9
10
11
12
13
using System.ComponentModel.DataAnnotations;
 
namespace MultipleModelsDemo.ViewModels
{
    public class TestTwoModel
    {
        [Required]
        public string PropertyThree { get; set; }
 
        [Required]
        public string PropertyFour { get; set; }
    }
}
In the controller a single action method is used to recieve the form posts. The action method MyEditActionOne uses the Index model. In this action method, the ModelState.IsValid property can be checked. Due to the model structure, separate forms can be sent for each child model, or the whole model as one. Note: Any properties defined in a parent class muss be valid if set as required.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Web.Mvc;
using MultipleModelsDemo.ViewModels;
 
namespace MultipleModelsDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new IndexViewModel();
            model.HeaderText = "Strongly typed model used here, no view bag";
            return View(model);
        }
 
        public ActionResult MyEditActionOne(IndexViewModel model)
        {
            if (ModelState.IsValid)
            {
                return View("Index", model);
            }
 
            throw new Exception("My Model state is not valid");
        }
    }
}
The html uses razor and can send either a form with just the first child model, or the second child model or the whole model as one. Only what is required for each form is validated. This is due to the model structure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@model MultipleModelsDemo.ViewModels.IndexViewModel
 
<div>
    @using (Html.BeginForm("MyEditActionOne", "Home"))
    {
        <div>
            <h4>Send Model One</h4>
            <fieldset>
                @Html.ValidationSummary(true, "ValidationSummary")
                <ol>
 
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyOne)
                        @Html.TextBoxFor(m => m.TestOne.PropertyOne)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyOne)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyTwo)
                        @Html.TextBoxFor(m => m.TestOne.PropertyTwo)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyTwo)
                    </li>
                </ol>
            </fieldset>
             
            <input class="btn" type="submit" value="Send" />
        </div>
    }
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<div>
    @using (Html.BeginForm("MyEditActionOne", "Home"))
    {
        <div>
            <h4>Send both Models</h4>
            <fieldset>
                @Html.ValidationSummary(true, "ValidationSummary")
                <ol>
 
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyOne)
                        @Html.TextBoxFor(m => m.TestOne.PropertyOne)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyOne)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestOne.PropertyTwo)
                        @Html.TextBoxFor(m => m.TestOne.PropertyTwo)
                        @Html.ValidationMessageFor(m => m.TestOne.PropertyTwo)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestTwo.PropertyThree)
                        @Html.TextBoxFor(m => m.TestTwo.PropertyThree)
                        @Html.ValidationMessageFor(m => m.TestTwo.PropertyThree)
                    </li>
                    <li>
                        @Html.LabelFor(m => m.TestTwo.PropertyFour)
                        @Html.TextBoxFor(m => m.TestTwo.PropertyFour)
                        @Html.ValidationMessageFor(m => m.TestTwo.PropertyFour)
                    </li>
                </ol>
            </fieldset>
 
            <input class="btn" type="submit" value="Send" />
        </div>
    }
</div>
As shown, it is very easy to implement multiple strongly typed models in a single view. Using this structure it would also be possible to implement a dynamic view with multiple forms or data.
Links: