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

Monday, 1 February 2016

What is MVC ?

                     Model View Controller(MVC) is one of architectural pattern for building  web application development. MVC  for building more granular development which gives more control on end to end web application (design,development,maintain).

                                       

 MVC Agenda

* Separation of concerns. (Model,View,Contoller).


In any application when user/client perform any operation on web page.
Every 3 opertions are mandatory.

1. Request processing
2. Maintaing state/behaviour
3. Response return



* Define roots.

                Asp.net MVC, Spring,Rails...are implementations of MVC patterned packages/frameworks for building more robost and reliable web application development SDK's.


        -- More radable and scable applications.
        --to avoid ugly URL and request processing.

*




 in simple words which there is no ready made binding controls and predefined events,

Wednesday, 28 November 2012

DataBinding in asp.net mvc?


DataBinding in ASP.NET MVC :

              Yes, In asp.net à all standard bidning controls are requires ListItem collection.EX: dropdown, radaiobutton,listbox..ect

Binding Items to DropDownList asp.net mvc

1st way

  List<string> languages = new List<string>();
            languages.Add("Chsarp");
            languages.Add("VisualBasic");
            languages.Add("FSharp");
            ViewData["languges"] = new SelectList(languages);  // as IEnumerable
            return View();



@Html.DropDownList("languges", "--select one--")  ----------loosely copuled

------------------------------------------------------------------------------------
2nd way


           SelectListItem list1 = new SelectListItem();
            list1.Text = "ONE";
            list1.Value = "one";

            SelectListItem list2 = new SelectListItem();
            list2.Text = "TWO";
            list2.Value = "two";

            List<SelectListItem> slist = new List<SelectListItem>();
            slist.Add(list1);
            slist.Add(list2);

            ViewData["key"] = slist;

            return View();

@Html.DropDownList("CategoryId", (IEnumerable<SelectListItem>)ViewData["key"])
// as IEnumerable

3rd way

            SelectListItem list1 = new SelectListItem();
            list1.Text = "ONE";
            list1.Value = "one";

            SelectListItem list2 = new SelectListItem();
            list2.Text = "TWO";
            list2.Value = "two";

            List<SelectListItem> slist = new List<SelectListItem>();
            slist.Add(list1);
            slist.Add(list2);

          
            return View(slist);

@model IEnumerable<SelectListItem>               // as IEnumerable

@Html.DropDownList("strings",Model)

------------------------------------------------------------------------------


IQueryable<SelectListItem> query = conobj.emps.Select(t => new SelectListItem { Text = t.EName, Value = t.ELocation, Selected = t.EId.Equals(2) });

            IEnumerable<SelectListItem> ier = query.AsEnumerable<SelectListItem>();

            return View(ier);
 
@model IEnumerable<SelectListItem>

@Html.DropDownList("strings",Model)

--------------------------------------------------------------------------------

   IQueryable<SelectListItem> d = conobj.emps.Select(t => new SelectListItem { Text = t.ELocation, Value = t.EName });
            IEnumerable<SelectListItem> j = d.AsEnumerable<SelectListItem>();
            return View(j);



@model IEnumerable<SelectListItem>

@Html.DropDownList("ssl",Model,"--select--")
-----------------------------------------------------------------------------------

   List<SelectListItem> items = new List<SelectListItem>();
   items.Add(new SelectListItem() { Text = "Test1", Value = "1", Selected = false });
   items.Add(new SelectListItem() { Text = "Test8", Value = "8", Selected = true });
   items.Add(new SelectListItem() { Text = "Test3", Value = "3", Selected = false });
   items.Add(new SelectListItem() { Text = "Test5", Value = "5", Selected = false });


  SelectList selectList = new SelectList(items, "Value", "Text");


NOTE:

any way but we must convert them as IEnumerable<SelectListItem> is must.




Sunday, 18 November 2012

ASP.NET MVC Get and Post request?


Yes, In web forms first request is by default is get request then post request. generally we get the from then
fill the form ---> finally submit to server.

asp.net engine---> no need to specify the action method in <form> tag. on render server will send the method name and postback form name. ---> once see the view source. // implictly done by asp.net engine

<form id="form1" action="Default.aspx" method="post">

</form>
yes, but comming asp.net mvc we need to specify the action and method names. in Every Controller we have

2 methods with same name--->


public ActionResult Create()
        {

            return View();           // method="GET"
        }

How asp.net mvc know when to use which method. by default we don't specify an attribute like [httpPost] then which consider as Get Action so first executes ---> Create method.

then after filling the form submit to server---> so

<input type="submit" value="Save" />----->Behaviour is POST

SO below POST method will be executed.

  [HttpPost]                                       // method="POST"
        public ActionResult Create(Employee collection)
        {
            try
            {
             
                conobj.emps.Add(collection);
                conobj.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

as well at runtime above method is called like below:



How to make a view as Strongly --typed and how Model property works?

yes, when we creating view --as strongly types which generates  a code like


@model MvcthreeApplicationDemo.Models.Employee

here 
 Model represents current type(Employee) all properties belongs to Employee is accessable here.

in case of Create ---we creating single employee at a time so 

@model MvcthreeApplicationDemo.Models.Employee   // single employee only



In case of List ----we are returning multiple employes so


@model IEnumerable<MvcthreeApplicationDemo.Models.Employee>  // multiple employees




Saturday, 17 November 2012

How to CRUD operations: ASP.NET MVC

Yes, we can perform CRUD operations in asp.net mvc framework. In this example I created one EmployeeController with Create,Edit,Delete,Details operations.

then Create a Model :



public class Employee
    {
        [Required]
        [DisplayName("Employee ID")]
        public int EId { get; set; }
        [Required]
        [DisplayName("Employee Name")]
        public string EName { get; set; }
        [Required]
        [DisplayName("Employee Location")]
        public string ELocation { get; set; }
    }

 then change the Route : to Employee in Global.acax page

   new { controller = "Employee", action = "Create", id = UrlParameter.Optional } 



 then goto every action and create their apporiate actions


Ex:
 Index --->Add view -->Index--Stronglytyped view-->View content-->Ok


this is the same for all actions in the controller : EmployeeController .


this I am working with a static List<Employee> collection to peform to perform CRUD operations:

public class EmployeeController : Controller
    {        
        Employee eobj;
        static List<Employee> elist = new List<Employee>();

        public ActionResult Index()
        {
          
            return View(elist);
        }
     
        public ActionResult Details(int id)
        {
            Employee empdetails = elist.First(t => t.EId == id);
            return View(empdetails);
        }       
        public ActionResult Create()
        {
 // Employee eobj = new Employee { EId = 1, EName = "AdrosTrolsen", ELocation = "USA" };  //design time asigned automatically


            return View();
        }
     
        [HttpPost]
        public ActionResult Create(Employee ecollection)
        {
            try
            {
  eobj = new Employee { EId = ecollection.EId, EName = ecollection.EName, ELocation = ecollection.ELocation };
                elist.Add(eobj);                 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
           
        public ActionResult Edit(int id)
        {
            Employee emp = elist.First(t=>t.EId == id);

         
            return View(emp);
        } 
        [HttpPost]
        public ActionResult Edit(int id, Employee collection)
        {
            try
            {               
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }     

        public ActionResult Delete(int id)
        {

            Employee empdelete = elist.First(t => t.EId == id);
            return View(empdelete);
        }

  
        [HttpPost]
        public ActionResult Delete(int id, Employee collection)
        {
            try
            {               
                 Employee edelete = conobj.emps.Find(id);
                conobj.emps.Remove(edelete);
                conobj.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }

 and index : 

<% foreach (var item in Model) { %>
   
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new {  id=item.EId   }) %> |
                <%: Html.ActionLink("Details", "Details", newid=item.EId    })%> |
                <%: Html.ActionLink("Delete", "Delete", new {   id=item.EId   })%>
            </td>
            <td>
                <%: item.EId %>
            </td>
            <td>
                <%: item.EName %>
            </td>
            <td>
                <%: item.ELocation %>
            </td>
        </tr>
   
    <% } %>
 as well like this in every link of Details,Edit,Delete...also change them.


For every request 

http://localhost:3866/Employee/Create
http://localhost:3866/Employee/Index
http://localhost:3866/Employee/Details
http://localhost:3866/Employee/Delete
        automatically route is prepred as per our request// but one route only first request in global.asax.



What ASP.NET MVC Route table ?


 ASP.NET MVC application. MVC is application development architure. MVC represents ---Model, View,Controller.
Simply--à Model-àrepresent a type. View-à User Interface, Controller--à User Actions.
Controller:
Controller is the responsable for handling user requests. Very Controller is coupled/tied with a View.
A controller can have more then one action. We need to specify the which action to perform we have specify as REST style. Based on type action request will be processed and their associated view will be returned to client.

EX:


Bydefault Route is prepared for Home(Controller) and Index(Action). If we run the asp.net mvc application  which is executed as per our Route (Route: RouteName,Controller,Action,parameters).

Action :

http://localhost:3866/Home/Index(default)

so  we need to specify which controller as well which action.
Parameters:

We can optionally specify the Parameters also.
Finally a RouteTable will be prepared as per our Requested URI


Demo:

HomeController
public ActionResult MyAction(int id)
{

            ViewData["MyValue"] = id;
            return View();---------------MyAction.aspx(view)
       
}
    MyAction.aspx

  <h2>MyAction</h2>

 Entered Value is:<%: ViewData["MyValue"] %>




How Route is prepared ?

yes, as per our question  For Every Request Based  Route table will be Prepared by RoutTable

Then specify the Route as

public ActionResult MyAction(int id)
{

            ViewData["MyValue"] = id;
            return View();---------------MyAction.aspx(view)
       
}


then Route in Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
           new { controller = "Home", action = "MyAction", id = UrlParameter.Optional }                         );

}






Here I specifies the Route is à Home(controller), action(MyAction),id(optional).

But MyAction requires --à a Parameter





Saturday, 4 August 2012

Difference between MVC- ViewData and ViewBag?

public abstract class ControllerBase : IController
{
public dynamic ViewBag { get; }
public ViewDataDictionary ViewData { get; set; }

}

ViewBag:

viewBag is a dynamic Property which is used to pass data from view to controller.
Like
            ViewBag.FirstName = "kasibabu";
            ViewBag.LastName = "viswanath";
            ViewBag.Age = 26;
            ViewBag.Address = ViewBag.FirstName + ViewBag.LastName; // Dynamic Property

            ViewData["Age"] = ViewBag.Age;  // which is key/valued collection.

so we can access the Data from view at Runtime.

Like
        @ViewBag.Address---------à kasibabuviswanadh // Runtime passing data
        @ViewData["Age"]---------à key/ value based collection.

In ViewBag which create an anonymous type at runtime then pass data dynamically to view.

come to ViewData which holds data like a Session which stores data to based on key.

ViewData :


ViewData is of type ViewDataDictionary. which is also used to pass data from control to view

As well how to

        public ActionResult Index()
        {

            List<string> countries = new List<string>();
            countries.Add("India");
            countries.Add("Usa");
            countries.Add("UK");
ViewBag.Countries = countries;         //   ViewData["countries"] = countries;

            return View();
        }
<h6>
   <ol title="Some countries">
      @foreach (var item in ViewBag.Countries)
      {
         <li> @item</li>
      }
    </ol>
</h6>

 //   ViewData["countries"] = countries;

<ol title="Some countries">
      @foreach (var item in ViewData["countries"] as List<string>) //weak -typing
      {
         <li> @item</li>
      }

    </ol>

Yes the above ViewData way while converting we need to specify as strings.
So we can cay this is not a tightly coupled view.


as well as strongly typed view also is possible with the help of specified Model.

@model IEnumerable<FutureisMVC.Models.RegisterModel>

@model IEnumerable<FutureisMVC.Models.CarModel>

----ect.


which is preferable is based on scenerio :