April 5, 2011

Code Example for ASP.NET MVC2.0

This is my first step towards learning ASP.NET MVC Architecture
Here I ll create a Student Form and Will save the form Data in Sqlserver database using ASP.NET MVC2.0

1.) Install ASP.NET MVC 2.0 for Visual Studio 2008 from the below link
http://www.microsoft.com/downloads/en/details.aspx?familyid=C9BA1FE1-3BA8-439A-9E21-DEF90A8615A9&displaylang=en

2.)First Create a New Project by selecting ASP.NET MVC2 Web Application Template

3.)Click Ok It will add sample application with two Views Home and Account
4.) We will Add Our Form Student within the same App
5.)Right click on Models Add new class StudentModel.cs
6.)Code On StudentModel.cs Create property corresponding to each Form Field + Write the Validation

Models/StudentModel.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data;
using System.Web.Mvc;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;


namespace TestMVCapplication.Models
{
    public class StudentModel
    {


        [Required(ErrorMessage = "* Required")]
        [StringLength (10,ErrorMessage="must be under 10")] 
        [RegularExpression ("^([a-zA-z\\s]{4,32})$",ErrorMessage ="Only Alphabets are allowed")]
        [DisplayName("Name")]
         public string Name { get; set; }


        [Required(ErrorMessage = "* Required")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Your email address contains some errors")]
        [DisplayName("Email address")]
        [RegularExpression("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$",ErrorMessage="Enter a Valid Email")]
        public string Email { get; set; }


        [Required(ErrorMessage = "* Required")]


        public string Comment { get; set; }




    }
}


7.)We’ll then add a “StudentController.cs” controller class to our project's Controllers folder that exposes two “GetStudent” action methods.  
The first action method is called when an HTTP-GET request comes for the /Student/Create URL.  It will display a blank form for entering Student data. 
 The second action method is called when an HTTP-POST request comes for the /Student/Create URL.  It maps the posted form input to a Student object, verifies that no binding errors occurred, and if it is valid will eventually save it to a database(Business Logic)


Controllers/StudentController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestMVCapplication.Models;
using System.Data;
using System.Data.SqlClient;

namespace TestMVCapplication.Controllers
{
    public class StudentController : Controller
    {
       


        SqlConnection connObj = new SqlConnection();
        DataSet ds;
        SqlCommand objCommand;
        SqlDataAdapter objAdapter;


        
        // GET: /Student/
        public ActionResult GetStudent()
        {
            return View();
        }

        
        [HttpPost]

        public ActionResult GetStudent(StudentModel model)
        {
            Response.Write(model.Name + model.Comment + model.Email);
            //code to insert data in DB using ADO.NET
            connObj.ConnectionString = "Data Source=.\\sqlexpress;Initial Catalog=TestMVC;Integrated Security=True";
         connObj.Open();
        SqlCommand comm = new SqlCommand("insert into student(name,email,comment) values(@name,@email,@comment)", connObj);
        
            comm.Parameters.Add("@name", SqlDbType.VarChar , 50).Value =model .Name ;
            comm.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = model.Comment;
            comm.Parameters.Add("@comment", SqlDbType.VarChar, 50).Value = model.Email;

        int result = comm.ExecuteNonQuery();
        if (result != 0)
            Response.Write(" added");
        else
            Response.Write("Error");

            return View();
        }

    }
}

8.)After we’ve implemented our controller, we can right-click within one of its action methods and choose the “Add View” command within Visual Studio – which will bring up the “Add View” dialog.  


Visual Studio will then generate a Getstudent.aspx view file for us under the \Views\student\ directory of our project.  See How we can use  new strongly-typed HTML helpers in ASP.NET MVC 2 (enabling better intellisense and compile time checking support):


9.) Design the form on Getstudent.aspx using HTMlHelper Class
Views/Student/GetStudent.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestMVCapplication.Models.StudentModel>" %>


<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
GetStudent
</asp:Content>


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">


    <h2>GetStudent</h2>




 <% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
        <fieldset>
             <legend>Student Detail</legend>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Name) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Name) %>
                <%= Html.ValidationMessageFor(m => m.Name) %>
            </div>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Email) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Email) %>
                <%=Html.ValidationMessageFor(m => m.Email) %>
            </div>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Comment) %>
            </div>
            <div class="editor-field">
                <%= Html.TextAreaFor(m => m.Comment, 10, 25, null) %>
                <%= Html.ValidationMessageFor(m => m.Comment) %>
            </div>
            <p>
                <input type="submit" value="Submit" />
            </p>
        </fieldset>
        <p id="result"><%=TempData["Message"] %></p>
    <% } %>
</asp:Content>

10)Add The link for Student in Site.Master

11.) Run The app



12) Click On Student


13) As  we’ve added the validation attributes to our studentModel.cs , let’s re-run our application and see what happens when we enter invalid values and post them back to the server:
The Html.ValidationMessageFor() helper will output the appropriate error message for any invalid model property passed to the view

14.)So far we saw  server-side validation – which means that our end users will need to perform a form submit to the server before they’ll see any validation error messages.
One of the feature of  ASP.NET MVC 2’s validation architecture is that it supports both server-side and client-side validation.  
To enable Client Side Validation
 we need to do is to add two JavaScript references to our view, and write one line of code:
  1. Add Reference of JS files in site.master


      2)Write Code in View to Enable client Side Validation


To see the client-side JavaScript support in action   Notice how we’ll get an immediate error message for our missing value without having to hit the server:

15.) Insert Valid Form Values Click on submit it will call the Post GetStudent Action Method and will insert the    record in DB






See the Record Updated in the DB
                         

10 comments:

  1. Nice article...Thanks a lot

    ReplyDelete
  2. nice post, keep continuing. n thank a lot its really helped me................

    ReplyDelete
  3. Hey can u plz help me by adding a post about how to bind a grid view in MVC?

    ReplyDelete
  4. I am getting an error like this:
    The parameterized query '(@DealID int,@DealAgreement varbinary(8000))insert into Agreemen' expects the parameter '@DealAgreement', which was not supplied.

    Can anybody give solution?

    ReplyDelete
  5. You may have to give ur code where are you executing the query to find out the error .

    ReplyDelete
  6. All functionality is working fine but validation not working , it shows the validation required but still entering the data into database.

    ReplyDelete
  7. I am looking for like this article. so thank u

    ReplyDelete
  8. I love reading an article that will make people think. Also, many
    thanks for allowing for me to comment!
    Also visit my webpage :: Ragazze russe Carattere

    ReplyDelete