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

May 19, 2011

There is no ViewData item with the key '--' of type IEnumerable

There is no ViewData item with the key 'Student-Id' of type IEnumerable<SelectListItem> 


I got the above error when I wrote below code to bind data in DropdownList.

In View
<%= Html.DropDownListFor(x =>.Student_Id,<SelectList>ViewData["StudentList"])%>


In Controller

 TestMVCEntities3 DBobj = new TestMVCEntities3();
 ViewData["StudentList"] = new SelectList(DBobj.Student, "Student_Id","Name");  
 return View();


I Resolved the above error by Using Model instead of ViewData in below manner


In View
<%= Html.DropDownListFor(x => x.Student_Id,Model.StudentList)%>


In Model
public IEnumerable<SelectListItem> StudentList { get; set; }


In Controller

 TestMVCEntities3 DBobj = new TestMVCEntities3();
 var model = new StudentMarksModel();
 model.StudentList = new SelectList(DBobj.Student, "Student_Id", "Name");
 return View(model);

May 18, 2011

Code Example ADO.NET Entity Framework "Insert Update Delete" data in MVC application


How we can use ASP.NET MVC Framework check this post

In the above Post example I have used ADO.NET to insert the data in SQLServer Db (Student Table)
Now In this post I 'll Insert and Update Data in Student_Marks table(Student_id,Marks)in One More view
Using ADO.NET Entity framework.

1.) Creating the ADO.NET Entity Data Model 
     Check the below post to create ADO.NET Entity Data Model.

2.) We will Add Our Form AddStudentMarks within the same App
3.)Right click on Models Add new class StudentmarksModel.cs
4.)Code On StudentMarksModel.cs Create property corresponding to each Form Field + Write the Validation 

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;


namespace TestMVCapplication.Models
{
    public class StudentMarksModel
    {


        [DisplayName("Marks")]
        [Required(ErrorMessage = "* Required")]
        public string  Marks { get; set; }


        public string Student_Id { get; set; }


        public IEnumerable<SelectListItem> StudentList { get; set; }


    }
}


5.)We’ll then add a “StudentMarksController.cs” controller class to our project's Controllers folder that exposes two “AddStudentMarks” action methods.  




The first action method is called when an HTTP-GET request comes for the /StudentMarks/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 /Studentmarks/Create URL.  It maps the posted form input to a StudentMarks object, verifies that no binding errors occurred, and if it is valid will eventually save it to a database(Business Logic)






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



namespace TestMVCapplication.Controllers
{
    public class StudentMarksController : Controller
    {
        //
        // GET: /StudentMarks/
        [HttpGet]
        public ActionResult AddStudentMarks()
        {
         
          TestMVCEntities3 DBobj = new TestMVCEntities3();

          //ViewData["StudentList"] = new SelectList(DBobj.Student, "Student_Id", "Name");

          
          //return View();

         //To set the Student Names in DropdownList
          var model = new StudentMarksModel();
          model.StudentList = new SelectList(DBobj.Student, "Student_Id", "Name");
               
                          
           return View(model);
            
        }



        [HttpPost]

        public ActionResult AddStudentMarks(StudentMarksModel model)
        {
           //Add Data Using Entity Framework in ADO.NET

            TestMVCEntities3 DBobj = new TestMVCEntities3();

            int StudentId = Convert.ToInt32(model.Student_Id);


            //Check If the reord exists with the Dropdownlist selcted value as Student_Id
            var record = DBobj.Student_Marks.FirstOrDefault(m => m.Student_Id == StudentId);
            
            //If record exists update it with the value entered in marks textbox
            if (record != null)
            {
                Student_Marks e = (from e1 in DBobj.Student_Marks

                                   where e1.Student_Id == StudentId

                                   select e1).First();
                e.Marks = int.Parse(model.Marks);
                DBobj.SaveChanges();

            }

            //If record doesn't exists Insert the new record
            else
            {
                Student_Marks sMarks = new Student_Marks();

                sMarks.Student_Id = int.Parse(model.Student_Id);
                sMarks.Marks = int.Parse(model.Marks);



                DBobj.AddToStudent_Marks(sMarks);
                DBobj.SaveChanges();
            }


            //To set the Student Names in DropdownList
            var modelsend = new StudentMarksModel();
            modelsend.StudentList = new SelectList(DBobj.Student, "Student_Id", "Name");


            return View(modelsend);
           
        }

    }
}

7.)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
Add  AddStudentMarks.aspx view file for us under the \Views\StudentMarks\ 
8.)Design the form on AddStudentMarks.aspx using HTMlHelper Class



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


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


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


    <h2>AddStudentMarks</h2>


<form id="form1" runat="server">
<% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
     <fieldset>
           <div class="editor-field">
                <%= Html.DropDownListFor(x => x.Student_Id,Model.StudentList)%>
                <%= Html.ValidationMessageFor(m => m.Student_Id) %>
           </div>
            
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Marks) %>
                <%= Html.ValidationMessageFor(m => m.Marks) %>
            </div>
             <p>
                <input type="submit" value="Submit" />
            </p>
        </fieldset>
        <p id="result"><%=TempData["Message"] %></p>
    <% } %>
    </form>
</asp:Content>


9)Add The link for Student in Site.Master



10) Run the app
11.)Click StudentMarks

      StudentList will be filled up from Student table in DropDownlist
     

12)select the name and insert Marks if The student_id already Exists in Student_Marks It will 
   update the record if it does not exist it will add new record with the selected Student_Id from drop Down and input marks

13.) See the Updated Record in DB

May 14, 2011

ASP.Net MVC Sample Application using ADO.Net Entity Framework

How we can use ASP.NET MVC Framework check this post
http://www.dotnetissues.com/2011/04/code-example-for-aspnet-mvc20.html

In the above Post example I have used ADO.NET to insert the data in SQLServer Db (Student Table)
Now In this post I 'll add one more view Where To Select the records from the above table I 'll
use ADO.NET Entity framework.

1.)Creating the ADO.NET Entity Data Model
In order to use the Entity Framework, you need to create an Entity Data Model. You can take advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a database automatically.
Follow these steps:


1)Right-click the Models folder in the Solution Explorer window and select the menu option Add, New Item.
2)In the Add New Item dialog, select the Data category
3)Select the ADO.NET Entity Data Model template, give the Entity Data Model the name Model1.edmx,
4)Click the Add button. Clicking the Add button launches the Data Model Wizard.
5)In the Choose Model Contents step, choose the Generate from a database option and click theNext button



6)In the Choose Your Data Connection step, select the MoviesDB.mdf database connection, enter the entities connection settings name TestMVEntities3, and click the Next button


8)In the Choose Your Database Objects step, select the TestMVC database table and click the Finishbutton


After you complete these steps, the ADO.NET Entity Data Model Designer (Entity Designer) opens.
Model1.designer.cs will be automatically generated and It will Map the Database and the tables as the
entity classes and To Communicate with the DB now we can Communicate with The entity classes objects
We can use EntitySQl query syntax or LINQ to Sql Below is the code sample for both.

To Select Records from student table using entity sql I added below highlighted code in StudentController.cs

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;
using System.Data .Objects ;


namespace TestMVCapplication.Controllers
{
    public class StudentController : Controller
    {
        SqlConnection connObj = new SqlConnection();
        DataSet ds;
        SqlCommand objCommand;
        SqlDataAdapter objAdapter;




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




        public ActionResult Viewstudent()
        {


            TestMVCEntities3 DBobj = new TestMVCEntities3();
               
             
                    //ENTITY SQL QUERY SYNTAX
                    ObjectQuery query = DBobj.CreateQuery<Student>("Select value s from student as s");
                    var res = query.Execute(MergeOption.NoTracking) as IEnumerable<Student>;
                    int i=0;
                    foreach (Student  c in res)
                    {
                      // Response .Write (c.Name);
                       ViewData["name"+i.ToString()] = c.Name;
                       ViewData["email" + i.ToString()] = c.Email;
                       ViewData["comment" + i.ToString()] = c.Comment;
                       i++;
                    }




                     //LINQ TO ENTITY QUERY
                     //var query1 = from Student  c in DBobj.Student
                     //               select c;


                     //foreach (Student  c in query1)
                     //       {
                     //          Response .Write (c.Name);
                     //       }


            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();
        }


    }


    
}




From the above Viewstudent I selected records from the Student Table and 
Inserted those iv ViewData to able to access them in the Viewstudent View
I added one View named Viewstudent.aspx in in views/Student




views/student/Viewstudent.aspx


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


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


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


    <h2>Viewstudent</h2>
   <% for (int i = 0; i <= ViewData.Count;i++ )
      { %>


     Name: <%= ViewData ["name"+i.ToString ()]%>
    <br />
     Email:<%= ViewData ["email"+i.ToString ()]%>
    <br />
     Comment:<%= ViewData ["comment"+i.ToString ()]%>
    <br />
     
        <hr />
<% } %>

</asp:Content>


To Link this View in Previous MVC Example's view I added the below highlighted line of code there 

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">




    <form id="form1" runat="server">




    <h2>GetStudent</h2>




 <% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
       <%= Html.ActionLink("ViewstudentData", "Viewstudent", "Student")%>
&nbsp;<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>
    <% } %>
    </form>
</asp:Content>


Now Run the application again and Click On Student Menu Link




Click On ViewStudentData Link
and you ll get the selected records in the view 





April 7, 2011

Code Example Creating a Custom Validation Attribute in ASP.NET MVC 2.0


The System.ComponentModel.DataAnnotations namespace includes a number of built-in validation attributes .
So far(In Previous Example) We have used  [Required], [StringLength], and [RegularExpression].
We can also create  own custom validation attributes by deriving from the ValidationAttribute base class within the System.ComponentModel.DataAnnotations namespace.  
Or We can  derive from any of the existing validation attributes just to modify the  functionality. 
So We Will Include One  more class in Previous StudentModel.cs


Now this Custom Validator can be used Like this


Before I was using Regular Expression Validation Attribute to validate the email.
Now I am using Email Attribute which is Custom Validation Attribute
Now To test it enter Wrong Email and see the Custom Validation Attribute in action.

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