Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Asp.NET MVC over Asp.NET Web Forms

I am asp.net Web Forms developer and i know the basics of Asp.net MVC. Developers talk about advantages of MVC but I haven't come across a clear or compelling description for using MVC over Asp.NET.

This is not duplicate question and i have gone through almost all similar question but did not get clear description more in relation with real life example. I do appreciate and expect the explanation of each and every question mentioned below with real life example please don't mark it as duplicate.

I know that you can not replace Asp.NET Web Forms with Asp.NET MVC still we have following advantages in MVC:

  1. Separation of concerns (SoC): We can achieve it in asp.net also by adding BAL component in fact in MVC we do have to isolate business logic from controller action methods.Is SoC only applicable for Model-View-Controller separation in MVC? then what about business logic. Please provide real life example which will consider both Web Forms and MVC.
  2. Enable full control over the rendered HTML: Web Forms also provide control over Html isn't it? Its considered that html rendering in Web Forms is more abstracted then what does html helper methods do in MVC. Anybody please explain it with example considering both Web Forms and MVC as i am getting more confused over this point.
  3. Enable Test Driven Development (TDD): If you have separated your Business logic into BAL then you have achieved TDD? Is there any scenario where MVC would be accurate choice over webforms? Please provide example for same
  4. No ViewState and PostBack events: We can manage viewstate in Web Forms which comes with cost of efforts, since in MVC we can maintain state by using Viewbag,Tempdata as web is stateless there is some mechanism that MVC maintains its state as hidden fields for Web Forms then how MVC Improves performance and page size in terms of statefullness? Example by considering Web Forms and MVC appreciated
  5. Easy integration with jQuery: "Asp.NET Web Forms generate its custom id for controls" this is the only consideration for ease of integration of JavaScript frameworks? if yes then we can use ClientIDMode in asp.net control in Web Forms
like image 369
Smack Avatar asked Apr 21 '14 10:04

Smack


2 Answers

1. Separation of concerns

SoC in MVC is not about separation business logic from UI. More importantly, it gives Controller main functions:

  • to fill View Model from Domain Model;
  • to handle View activity;
  • to show views depending on Domain logic.

View is responsible only for data representation in MVC.

It makes testing very simple as Controller operates pure View Model classes, opposed to WebForms which operates events and Form.

In WebForms View handles all UI activity and it basically makes decisions about scenario flow.

Here I'd like to mention that terms of View Model and Domain Model are different. Domain Model is a term describing all the services, Business logic and DAL hidden from Controller with some facade. And View Model is a class that encapsulates data required by View. It may be shared by Domain Model in simple cases. Why two classes?

Here are similar code snippets of ASP.NET MVC and WebForms doing the same things: 1) get data 2) handle data submission. In both cases I assume that IDomainModel is injected.

MVC:

public class SomeController : Controller
{
    // injected
    public IDomainModel Domain { get; set; }

    public ViewResult Edit()
    {
        var record = Domain.GetRecord(1);
        var dictionary = Domain.GetSomeDictionary();
        var model = new SomeViewModel(record, dictionary);

        return View(model);
    }

    [HttpPost]
    public ActionResult Edit(SomeViewModel model)
    {
        if (ModelState.IsValid)
            // save
            return RedirectToAction("Result");
        else
            return View(model);
    }
}

WebForms:

public partial class SomePage : System.Web.UI.Page
{
    // injected
    public IDomainModel Domain { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        var record = Domain.GetRecord(1);
        var dictionary = Domain.GetSomeDictionary();

        RecordId.Text = record.Id.ToString();
        RecordName.Text = record.Name;
        RecordDescription.Text = record.Description;

        DicValue.DataSource = dictionary;
        DicValue.DataValueField = "Id";
        DicValue.DataTextField = "Value";
        DicValue.SelectedValue = record.DictionaryEntryId.ToString();
        DicValue.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        var record = new RecordModel
        {
            Id = Int32.Parse(this.RecordId.Text),
            Name = this.RecordName.Text,
            Description = this.RecordDescription.Text,
            DictionaryEntryId = Int32.Parse(this.DicValue.Text)
        };
        // save
    }
}

Testing MVC controller Edit GET is incredibly simple:

[TestMethod]
public void EditGetTest()
{
    SomeController target = new SomeController();

    var record = new RecordModel { Id = 1, Name = "name1", Description = "desc1", DictionaryEntryId = 1 };
    var dictionary = new List<SomeDictionaryEntry>
    {
        new SomeDictionaryEntry { Id = 1, Value = "test" }
    };

    target.Domain = new SimpleMVCApp.Models.Fakes.StubIDomainModel()
    {
        GetRecordInt32 = (id) => { return record; },
        GetSomeDictionary = () => { return dictionary; }
    };

    var result = target.Edit();

    var actualModel = (SomeViewModel)result.Model;
    Assert.AreEqual(1, actualModel.Id);
    Assert.AreEqual("name1", actualModel.Name);
    Assert.AreEqual("desc1", actualModel.Description);
    Assert.AreEqual(1, actualModel.DictionaryEntryId);
}

To test WebForms events we need to make a lot of changes and assumptions: we need to make the methods public, we need to initialize Form and its controls. It results in heavy hard-read tests which are impossible for 3) TDD.

2. Enable full control over the rendered HTML

I think this statement is a little bit exaggeration. Only HTML can give full control over rendered HTML. As for HtmlHelpers, DisplayTemplates and EditorTemplates, though the team made major improvements over 6 versions of the framework, it's still sometimes annoying to transform additionalViewData into html attributes.
For example, to pass some html attributes to an input you can't use @Html.EditorFor, you'll have to use @Html.TextBoxFor.
In the same time in ASP.NET you can specify any attributes on any elements and they will just render.

MVC:

Wrong:

@Html.EditorFor(m => m.Name, new { MySuperCustomAttribute = "Hello" })

Correct:

@Html.TextBoxFor(m => m.Name, new { MySuperCustomAttribute = "Hello" })

ASP.NET:

<asp:TextBox runat="server" ID="RecordName" MySuperCustomAttribute="hello"></asp:TextBox>

3. Enable Test Driven Development (TDD)

I think this statement is about testing of Controller vs Code-Behind. I covered this in 1.

4. No ViewState and PostBack events

ViewBag and ViewData are weak-typed facilities to pass data between Controller and Views. They are rendered as elements, nothing similar to ViewState. For example, in my View I initialize ViewBag.Title = "EditView"; which allows me to use this string on the Layout Page: <title>@ViewBag.Title - My ASP.NET MVC Application</title>. On the page it looks just like this <title>EditView - My ASP.NET MVC Application</title>

As to TempData, Session and Application, they are stored on server side. It's not rendered to page at all.

5. Easy integration with JQuery

I don't see how integration with JQuery becomes easier for MVC. Here is how we integrate JQuery into WebForms:

<script src="Scripts/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function () {
    $('#DicValue').change(function () {
        $('#ChosenValue').text($('#DicValue option:selected').val());
    });
});
</script>

And here is almost the same snippet for ASP.NET MVC:

@section scripts{
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
$(document).ready(function () {
    $('#DictionaryEntryId').change(function () {
        $('#ChosenValue').text($('#DictionaryEntryId option:selected').val());
    });
});
</script>
}

There is another point to mention about JQuery here: as ASP.NET MVC is pretty Opinionated framework, it becomes somewhat restrictive for extensive JS usage. It was originally designed for Scaffold Templates based development, and it is best with it. JQuery is good for ajax requests and for some minor logic in ASP.NET MVC, but when you start using it extensively, you end up with two controllers for every view: a C# one and a JS one. Hello, Unit Testing! Also JQuery(UI) is very good with its rich set of UI controls.

ASP.NET is designed with Postbacks in mind and they dictate you the basic application model. However, there are also different UI Toolkits for ASP.NET to make an application more dynamic and there is still some place for JQuery.

Wow, that was a long answer. Hope it'll help.

like image 98
d_z Avatar answered Oct 31 '22 05:10

d_z


Ok.

I am developing applications in both frameworks i.e. Webforms and MVC, will be explaining things based on my experience.

Discipline is the most important thing that needs to be followed with any Architecture you are working on.

If you follow MVC correct and as per standards life would be super simple.

Lets go point by point.

Separation of concerns (SoC): MVC provide Clean, organized and granular solution at various levels e.g. There are multiple helper classes which hooks and does help in late bindings, you can mock controller using various plugins. Easy to develop Helper classes.

Enable full control over the rendered HTML Basically in MVC we have HTML in its native format, so you have more control over it and how it matters is it speeds up Page Load when you have lot of controls and data that are coming on the page. And it matters when we are going with Web form architecture.

Enable Test Driven Development (TDD): With discipline you can do it in both Architecture

No ViewState and PostBack events: Viewstate puts extra load on page and in web forms when you see source of a page having lots of controls, grid etc, you will see huge viewstate. If there is no viewstate life is just simple. ViewData is at client side whereas others are at server side.

Easy integration with Jquery: Indeed, MVC3, 4 have super better support for JQuery. There are lot of Predefined JQueries that are already introduced in templates.

Other than above points some additional points Bundling Refreshed and modernized default project templates Better support of Mobile applications Fast development Code reusability Least coupling within Layers Good support to Ajax

Have a look at few links

http://www.codeproject.com/Articles/683730/New-Features-in-ASP-NET-MVC http://www.asp.net/mvc/tutorials/hands-on-labs/whats-new-in-aspnet-mvc-4

Difference between ASP.NET MVC 3 and 4?

like image 39
Nipun Ambastha Avatar answered Oct 31 '22 04:10

Nipun Ambastha