5 August 2013

MVC 3 Ajax Json Sample

MVC 3 Ajax Json Sample 





























Create model name PersonDetails.cs
using System.Collections.Generic;

namespace MVCJsonAjax.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public List< Address > Addresses { get; set; }
    }

    public class Address
    {
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string ZipCode { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }

}


Create Controller - SaveController.cs

using System.Web.Mvc;
using MVCJsonAjax.Models;

namespace MVCJsonAjax.Controllers
{
    public class SaveController : Controller
    {
        //
        // GET: /Save/

        [ActionName("SaveData"),HttpGet]
        public ActionResult SaveData()
        {
            return View();
        }


     [ActionName("SaveData"), HttpPost]
        public JsonResult SaveData(Person objPerson,Address objAddress)
         {

             JsonResult result = new JsonResult();

            // Save logic - save person and address details

             result.Data = "Saved Successfully";
             return result;
        }
 
    }
}

Create View for ActionResult SaveData()

@using MVCJsonAjax.Models
@{
    ViewBag.Title = "SaveData";
}
< h2 >
    Save Data< /h2 >

    < div>
    < div id="message" >
    < /div>
< /div >


< script type =" text/javascript ">
    $(document).ready(function () {
         
        $('#btnSubmit').click(function () {
         
            var Person =
            {
                FirstName: $('#Item1_FirstName').val(),
                LastName: $('#Item1_LastName').val()
            };

            var Address =
                {
                    Line1: $('#Item2_Line1').val(),
                    Line2: $('#Item2_Line2').val(),
                    ZipCode: $('#Item2_ZipCode').val(),
                    City: $('#Item2_City').val(),
                    State: $('#Item2_State').val(),
                    Country: $('#Item2_Country').val()
                };

                var obj = { "Per": Person, "Add": Address};

            $.ajax({
                url: '/Save/SaveData',
                type: "POST",
                data:JSON.stringify({objPerson: Person ,objAddress: Address }),              
                cache: false,
                dataType: "json",
                contentType: "application/json;charset=utf-8",
                success: function (result) {
                    $('#message').html(result).fadeIn();

                }
            });

            return false;
        });
    });




@model Tuple< Person, Address >
@using ( Html.BeginForm() )
{
    < table >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item1.FirstName)
                @Html.TextBoxFor(m => m.Item1.FirstName)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item1.LastName)
                @Html.TextBoxFor(m => m.Item1.LastName)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.Line1)
                @Html.TextBoxFor(m => m.Item2.Line1)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.Line2)
                @Html.TextBoxFor(m => m.Item2.Line2)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.ZipCode)
                @Html.TextBoxFor(m => m.Item2.ZipCode)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.City)
                @Html.TextBoxFor(m => m.Item2.City)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.State)
                @Html.TextBoxFor(m => m.Item2.State)
            < /td >
        < /tr >
        < tr >
            < td >
                @Html.LabelFor(m => m.Item2.Country)
                @Html.TextBoxFor(m => m.Item2.Country)
            < /td >
        < /tr >
        < tr >
            < td >
                <  input type="submit" value="Submit" id="btnSubmit" / >
            < /td >
        < /tr >
    < /table >

}



4 August 2013

Dynamic v. Strongly Typed Views in MVC C# Razor Engine

Dynamic vs. Strongly Typed Views

Dynamic
Because we’re using a dynamic and not a strongly typed view, intellisense doesn’t help us. The completed code is shown below:

@model dynamic
         
@ {
    ViewBag.Title = "IndexNotStonglyTyped";
}

Index Not Stongly Typed< /h2 >



< p >
 < ul >
@foreach (var blog in Model) {
   < li >
    < a href="@blog.URL">@blog.Name< /a >
   < /li >  
}
 < /ul >

< /p >

Strongly Typed Views
When it is strongly typed view.

5658.StrongView[1]

Inside the new view template we get intellisense support.

7002.intellesince[1]


Handle Multiple Submit button in MVC C#

Handle Multiple Submit button in MVC C#

View
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
< input type="submit" name="submitButton" value="Send" / >
< input type="submit" name="submitButton" value="Cancel" / >

<% Html.EndForm(); %>

Controller
public class MyController : Controller {
    public ActionResult MyAction(string submitButton) {
        switch(submitButton) {
            case "Send":
                // delegate sending to another controller action
                return(Send());
            case "Cancel":
                // call another action to perform the cancellation
                return(Cancel());
            default:
                // If they've submitted the form without a submitButton,
                // just return the view again.
                return(View());
        }
    }

    private ActionResult Cancel() {
        // process the cancellation request here.
        return(View("Cancelled"));
    }

    private ActionResult Send() {
        // perform the actual send operation here.
        return(View("SendConfirmed"));
    }

}






Delegates Example in C#

//Delegates Example in C#

using System;
using System.Windows.Forms;

namespace DelegatesTesting
{
    public partial class DelegatesTest : Form
    {
        public DelegatesTest()
        {
            InitializeComponent();
        }



        //Delegate Declaration
        public delegate int PointtoAddFunction(int i, int j);
     
        private void btnSubmit_Click(object sender, EventArgs e)
        {

            //Point the Delegate object with Method
            PointtoAddFunction handler = AddFunction;

            //Invoke the Method
            MessageBox.Show(handler(10, 12).ToString());

        }

        //Method
        public int AddFunction(int i, int j)
        {
            return i + j;
        }    
    }
}



Datatable to List in C# using Linq

Datatable to List in C# using Linq

//StudentDetails Class with Entity Details
 public class StudentDetails
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
        public string ClassName { get; set; }
        public string Section { get; set; }
    }
  

//Dataaccess part, Microsoft Sqlhelper class  used
 public List GetStudentDetails(int studentID)
        {
            DataSet ds = new DataSet();
            SqlParameter[] SqlParam = null;
            SqlParam = new SqlParameter[1];
            SqlCommand SqlCmd = new SqlCommand();
            List objStud = new List();
            try
            {
                SqlParam[0] = new SqlParameter("@StudentID", SqlDbType.Int);
                SqlParam[0].Value = studentID;
                SqlHelper.FillDataset(DBconnection(), CommandType.StoredProcedure, "usp_Get_StudentDetails", ds, new string[] { "Display" }, SqlParam);
               
 objStud = ds.Tables[0].AsEnumerable().Select(data => new StudentDetails() { StudentID = (int)data["StudentID"], StudentName = (string)data["StudentName"], ClassName = (string)data["ClassName"], Section = (string)data["Section"] }).ToList();
                return objStud;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (ds != null)
                {
                    ds.Dispose();
                }
                objStud = null;
            }
        }


MVC Menu

MVC Menu

1. MVC Programming Model in Asp.net

2. Setting the Default Page or Route in MVC application


3. Difference between Asp.Net MVC and Web Forms


4.ViewBag, ViewData, TempData and View State in MVC

5.Alternative to View State in MVC in Asp.net

6.Handle Multiple Submit button in MVC C#

7.Html.TextBox vs Html.TextBoxFor in MVC

8.Html.RenderPartial vs Html.Partial, Html.RenderAction vs Html.Action





3 August 2013

ASP.Net Page Life Cycle Events

ASP.Net Page Life Cycle Events:

At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.

Following are the page life cycle events:

PreInit  PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.

Init  Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.

InitComplete InitComplete event allows tracking of view state. All the controls turn on view-state tracking.

LoadViewState  LoadViewState event allows loading view state information into the controls.

LoadPostData  during this phase, the contents of all the input fields defined with the
tag are processed.

PreLoad  PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.

Load the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.

LoadComplete  the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.

PreRender  the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.

PreRenderComplete  as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.

SaveStateComplete  state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.


UnLoad  the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.


Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...