Overview
In the last couple of weeks I was just randomly going through a questionnaire section and found out there are many questions on MVC, particularly at the beginner level, or newbie level to ASP.NET you could say. There are many question about which is best, webforms or MVC, and if MVC, which version. As there are some nice articles which are related to MVC on C# Corner, this article will brief you about MVC, versions, a sample application, and answer the question: Why MVC?
Introduction
Today if you do market research the demand for MVC is huge and it's growing in numbers. Each and every company these days needs a MVC developer because whenever a new project for development comes they just want to develop their product in MVC. MVC Version 5 has been released with new features and the popularity of MVC is growing day by day. So let’s start.
If your existing project is in webforms and you find it perfectly normal, you will say why MVC, why not webforms? This URL here will give you a perfect picture as to why.
MVC (Model-View-Controller)
First let's see a simple diagram to give you an idea of how MVC Works.

As you can see in the above simple representation of how MVC works you see IIS, as MVC is a framework that is used to build web applications.
Model
Model is the part of your application that handles all logic sections; such as a request from user to insert or retrieve data from database.
View
Views are created from Model Data and the main role of View is display data to Users.
Controller
This handles all validations from users, reads data from view and also sends data to Model.
- So let's start with an ASP.NET MVC application; before that download the setup of MVC. To download the setup of MVC go to this link and just download -- it’s a very simple wizard, just click next and MVC setup will be installed. Refer to this URL for download.
- After installation just go your control panel and make sure it's successfully installed.

Microsoft Asp.NET MVC 4 is successfully installed. Now, its time to create an application.
Open Visual Studio ->File->New Project.
Select ASP.NET MVC 4 Web Application ->Give Suitable name as MVCTestApplication.

Now select Empty Application and Click Ok.
- Now you will see this:
Controllers, Models, and Views got created in our application. By default, our controller does not have any file so we add a new file in a controller.
- Right Click on Controller->Add->Controller.

- Name the controller as HomeController and Click ok.

- Now you will see this when you Click Ok:

Now here HomeController is our Class and Action is Index. If you write any code in actionable index, it will be rendered on the page . Now we will see HomeController is called by default.
- In App_Start when you see Route.Config File you will see the following code.

We will see a version of our MVC, and see which version it's using as we had selected MVC 4.
- HomeController.cs

We will see which version of MVC -- just run the solution:
- You can also Check in the references folder system.web.mvc

- Now we will Create a Hello World example

- Just run the application and you will see the following output.

Now just type the following URL: http://localhost:49414/Home/Index.

- You will see the same output is getting displayed:

- Now we will write another action method and see what is getting displayed.

- As you can see I had written another Action Method HelloAll() now we will run the application and see what is getting displayed.

- You will see Hello Csharpcorner got displayed -- why? Now go to RouteConfig.cs file and see that our Home Controller and Index action method is called by default . Now we will change the Action Method in URL and see what happens.

- This File says that default document get loaded as our default document here is HomeController and action is Index.
- Just Type this URL.

You will see the output as,

Our HellAll() Action Method now has been invoked and How Are You? has been displayed . You can also change RouteConfig.cs File.
- Let's rename our Index() Action Method and see what output it generates

I renamed it to IndexTest() . Now run application .

Now instead of displaying Hello Csharpcorner we got an error: resource not found. Why? Because we renamed our Action method and we didn’t configure in our Routecinfig file.
- Rename the Action method as Index().
Conclusion
This is all about a basic MVC application. In the next article I will explain more about controllers, models and views. Hope this was helpful to those who are new to MVC.

Prasun GuptaPosted Feb 14, 2020, 11:48 PM
@model IEnumerable<WebApplication8.Models.Medicine> @{ ViewBag.Title = "View"; Layout = "~/Views/Shared/_Layout.cshtml"; //WebGrid grid = new WebGrid(Model, rowsPerPage: 5); <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script> $(document).ready(function () { //Call EmpDetails jsonResult Method $.getJSON("/Home/grid", function (json) { var tr; //Append each row to html table for (var i = 0; i < json.length; i++) { tr = $('<tr/>'); tr.append("<td>" + json[i].Medicinename + "</td>"); tr.append("<td>" + json[i].Brand + "</td>"); tr.append("<td>" + new Date((json[i].ExpiryDate).substring(6, 19)) + "</td>"); tr.append("<td>" + json[i].Price + "</td>"); tr.append("<td>" + json[i].Quantity + "</td>"); tr.append("<td>" + json[i].Notes + "</td>"); $('table').append(tr); } }); }); //$(document).ready(function () { // getDateFromAspNetFormat(date: string): number { // const re = /-?\d+/; // const m = re.exec(date); // return parseInt(m[0], 10); // } //} </script> } <h2>View</h2> <p> @Html.ActionLink("Create New", "Create") </p> <style type="text/css"> .table { margin: 4px; border-collapse: collapse; width: 300px; } .header { background-color: gray; font-weight: bold; color: #fff; } .table th, .table td { border: 1px solid black; padding: 5px; } </style> @*@grid.GetHtml( tableStyle: "table", // applying style on grid fillEmptyRows: true, //show empty row when there is only one record on page to it will display all empty rows there. headerStyle: "header", //applying style. footerStyle: "grid-footer", //applying style. mode: WebGridPagerModes.All, //paging to grid firstText: "<< First", previousText: "< Prev", nextText: "Next >", lastText: "Last >>", columns: new[] // colums in grid { grid.Column("Medicinename"), //the model fields to display grid.Column("Brand" ), grid.Column("ExpiryDate"), grid.Column("Price"), grid.Column("Quantity"), grid.Column("Notes"), })*@ <table class="table table-bordered table-condensed table-hover table-striped"> <thead> <tr> <th>Medicinename</th> <th>Brand</th> <th>ExpiryDate</th> <th>Price</th> <th>Quantity</th> <th>Notes</th> </tr> </thead> <tbody></tbody> </table> @*<p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Medicinename) </th> <th> @Html.DisplayNameFor(model => model.Brand) </th> <th> @Html.DisplayNameFor(model => model.ExpiryDate) </th> <th> @Html.DisplayNameFor(model => model.Price) </th> <th> @Html.DisplayNameFor(model => model.Quantity) </th> <th> @Html.DisplayNameFor(model => model.Notes) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Medicinename) </td> <td> @Html.DisplayFor(modelItem => item.Brand) </td> <td> @Html.DisplayFor(modelItem => item.ExpiryDate) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.DisplayFor(modelItem => item.Quantity) </td> <td> @Html.DisplayFor(modelItem => item.Notes) </td> <td> @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }) </td> </tr> } </table>*@
Prasun GuptaPosted Feb 14, 2020, 11:47 PM
Using System;using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WebApplication8.Models; using Newtonsoft.Json.Linq; using System.IO; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Threading.Tasks; namespace WebApplication8.Controllers { public class HomeController : Controller { private string jsonFile = @"C:\Users\p\source\repos\WebApplication8\WebApplication8\bin\JSONFile.json"; public ActionResult Index() { ViewBag.Title = "Home Page"; return View("Index"); } [HttpGet] //public ActionResult grid() public async Task<JsonResult> grid() { using (HttpClient httpclntobj = new HttpClient()) { string result = string.Empty; httpclntobj.BaseAddress = new Uri("http://localhost:55242/"); HttpResponseMessage rspnsemessage = await httpclntobj.GetAsync("api/values/5"); //var res = rspnsemessage.Result; //var rspnsemessage = new HttpResponseMessage(); if (rspnsemessage.IsSuccessStatusCode == true) { var empresponse = rspnsemessage.Content.ReadAsAsync<int>().Result; } } List<Medicine> lmd = new List<Medicine>(); // creating list of model. var json = System.IO.File.ReadAllText(jsonFile); var jObject = JArray.Parse(json); string jsonstring = Convert.ToString(jObject); //JArray jObjectArray = (JArray)jObject[""]; if (jObject.Count > 0) { lmd = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Medicine>>(jsonstring, new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat }); //foreach (Medicine lm in lmd) //{ // lm.ExpiryDate = //} //lmd.Add(new Medicine //{ // Medicinename = jObject["Medicinename"].ToString(), // adding data from dataset row in to list<modeldata> // Brand = jObject["Brand"].ToString(), // ExpiryDate = jObject["ExpiryDate"].ToString(), // Price = Convert.ToDouble(jObject["Price"]), // Quantity = Convert.ToInt16(jObject["Quantity"]), // Notes = (jObject["Notes"]).ToString(), //}); } //DataSet ds = new DataSet(); //Connection.Connection con = new Connection.Connection(); // connection to getdata. //ds = con.mydata(); // fill dataset //foreach (DataRow dr in ds.Tables[0].Rows) // loop for adding add from dataset to list<modeldata> //{ //lmd.Add(new Medicine //{ // Medicinename = "MedicineName", // adding data from dataset row in to list<modeldata> // Brand = "BrandName", // ExpiryDate = "21-06-1988", // Price = 12.12, // Quantity = 12, // Notes = "Notes" //}); //} //return View("Index", lmd); return Json(lmd, JsonRequestBehavior.AllowGet); } public ActionResult Create() { return View("CreateMedicine"); } [HttpPost] public ActionResult Create(Medicine newRecord) { List<Medicine> lmd = new List<Medicine>(); var json = System.IO.File.ReadAllText(jsonFile); var jObject = JArray.Parse(json); string jsonstring = Convert.ToString(jObject); lmd = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Medicine>>(jsonstring); if (ModelState.IsValid) { lmd.Add(new Medicine { Medicinename = newRecord.Medicinename, // adding data from dataset row in to list<modeldata> Brand = newRecord.Brand, ExpiryDate = newRecord.ExpiryDate, Price = newRecord.Price, Quantity = newRecord.Quantity, Notes = newRecord.Notes }); String jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(lmd, new IsoDateTimeConverter { DateTimeFormat = "MM/dd/yyyy" }); System.IO.File.WriteAllText(jsonFile, jsonContent); return RedirectToAction("Index"); //return View("Index"); } else { return View("Index"); } } } }
Kanhaiya KumawatPosted Sep 19, 2018, 3:48 AM
Really helpfull akshaysir
Ravi KandelPosted Jul 14, 2016, 12:04 PM
Thanks for sharing.
Shobana JPosted Jul 7, 2016, 7:02 AM
Good share
Akshay PhadkePosted Jun 29, 2016, 6:19 AM
Thankyou EveryOne :)
Biplab BiswasPosted Jun 28, 2016, 9:15 AM
Nice Article..
Thiruppathi RPosted Jun 27, 2016, 9:46 AM
Nice..
Debasis SahaPosted Jun 27, 2016, 2:55 AM
Nice one..
RajaPosted Jun 27, 2016, 12:29 AM
Good One..
Vignesh ManiPosted Jun 26, 2016, 4:46 PM
Nice
Ankur MistryPosted Jun 26, 2016, 7:10 AM
Nice share
Upendra Pratap ShahiPosted Jun 26, 2016, 4:24 AM
Nice explain..
Prasanna MuraliPosted Jun 25, 2016, 10:33 PM
Nice one....
kalu singh raoPosted Jun 25, 2016, 2:39 PM
Nice...
NitinPosted Jun 25, 2016, 12:13 PM
Good one