May 31, 2011

Code Sample for Transformation in WPF



<Page x:Class="TestWPF.ExTransofrm"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ExTransofrm">
    <Grid>
       
        <TextBlock Text=" TRANSFORM TEXT" FontSize="20" FontWeight="Bold">
            <TextBlock.RenderTransform >
                <TransformGroup >
                    <RotateTransform Angle=" 45"></RotateTransform>
                    <SkewTransform AngleX=" 20" AngleY=" 20"></SkewTransform>
                    <TranslateTransform X="20" Y="60"></TranslateTransform>
                    <ScaleTransform ScaleX="1" ScaleY="1"></ScaleTransform>
                    
                    
                </TransformGroup>
             </TextBlock.RenderTransform>
            
     
        </TextBlock>
    </Grid>
</Page>

Below will be the transformed TextBlock

Code Sample to animate the button using Storyboard elemnets in WPF

Below is the sample code to Animate the button (Change the width,Change the Background color,Change the border color ) on Mouse Over



<PageFunction
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib" 
    x:Class="TestWPF.ExAnimation1"
    x:TypeArguments="sys:String"
    Title="ExAnimation1">
    <StackPanel>
        <StackPanel.Triggers>
            <EventTrigger RoutedEvent="Rectangle.MouseEnter">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetName="btnAnimate" 
                        Storyboard.TargetProperty="Width">
                            <DoubleAnimation From="120"
                               To="180" 
                               Duration="0:0:2"/>
                        </Storyboard>
                    </BeginStoryboard>
                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetName="btnAnimate" 
                        Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)">
                            <ColorAnimation From="orange"
                              To="Blue"
                              By="Beige" 
                              Duration="0:0:5" />
                        </Storyboard>
                    </BeginStoryboard>


                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetName="btnAnimate" 
                        Storyboard.TargetProperty="BorderBrush.Color">
                            <ColorAnimation From="Black"
                              To="Orange"
                              By="Red" 
                              Duration="0:0:5" />
                        </Storyboard>
                    </BeginStoryboard>


                </EventTrigger.Actions>
            </EventTrigger>
        </StackPanel.Triggers>
        <Button Name="btnAnimate" 
            Width="120"
            Height="50"
            Margin="40"
            Background="OrangeRed" BorderBrush="Cyan">
          ANIMATE
            
        </Button>
        
    </StackPanel>
    
</PageFunction>

May 30, 2011

Code Sample for Content Template in WPF




 First of all to know how to create WPF Browser App check the below post

Below is the code to design elliptical button in WPF Application using Control Template

ExControlTemplate.xaml

<Page x:Class="TestWPF.ExControlTemplate"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ExControlTemplate">


    <Grid>
        <Button Content=" Elliptical Button"  Width="100" Height="50" Style="{StaticResource EllipseButton}" />
          
           
        </Grid>
    


</Page>


App.xaml

<Application x:Class="TestWPF.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="ExControlTemplate.xaml">
    <Application.Resources>
        <Style x:Key="myStyle" TargetType="Button">
            <Setter Property="Background" Value="Orange" />
            <Setter Property="FontStyle" Value="Italic" />
            <Setter Property="Padding" Value="8,4" />
            <Setter Property="Margin" Value="4" />
        </Style>
        
        <Style x:Key="EllipseButton" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            
                            <Ellipse Fill="{TemplateBinding Background}"
                             Stroke="{TemplateBinding BorderBrush}"/>
                            <ContentPresenter HorizontalAlignment="Center"
                                          VerticalAlignment="Center" />
                            
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
              
                </Setter>
         
        </Style>
    </Application.Resources>
</Application>




Run the app and you 'll see the button


Controls in WPF are separated into logic, states, events ,properties and template
Template  defines the visual appearance of the control.
nThe wireup between the logic and the template is done by DataBinding.


Code Example to set Style on WPF Browser Application/XBAP Application

To Create WPF Browser Application/XBAP Application Go to New Project in VS2008 or later versions
Select Template WPFBrowserApplication and Click OK.



This will create a XBAP(XAML Browser Application) with some files
page.xaml(Design Page Here), App.xaml(Application configurations here)

2.)To add a new page Right click On Solution Explorer and from new Click on Page, Give Name and add it in the Application


3.) Below is the sample code To set Style on a page  (A style consists of a list of setters)


ExStyle2.xaml

<Page x:Class="TestWPF.ExStyle2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ExStyle2">


    <StackPanel Orientation="Vertical"  VerticalAlignment="Top">
        <Button Style="{StaticResource myStyle}" Height=" 50" Width="50">SEE</Button>
        <Button Style="{StaticResource myStyle}" Height=" 50" Width="50">WPF</Button>
        <Button Style="{StaticResource myStyle}" Height=" 50" Width="50">STYLES</Button>
        </StackPanel>
  
    
</Page>

Here in the above code Style setter is myStyle which is defined in App.xaml 


 App.xaml

<Application x:Class="TestWPF.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="ExStyle2.xaml">
    <Application.Resources>
        <Style x:Key="myStyle" TargetType="Button">
            <Setter Property="Background" Value="Orange" />
            <Setter Property="FontStyle" Value="Italic" />
            <Setter Property="Padding" Value="8,4" />
            <Setter Property="Margin" Value="4" />
        </Style>
        
        <Style x:Key="DialogButtonStyle" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Ellipse Fill="{TemplateBinding Background}"
                             Stroke="{TemplateBinding BorderBrush}"/>
                            <ContentPresenter HorizontalAlignment="Center"
                                          VerticalAlignment="Center"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Application.Resources>
</Application>


StartupUri attribute is used to set the StartUpPage of the App.






Run the app an see the Style applied to the page


May 26, 2011

Code to Bind Data from SqlDataReader to Grid View

Following is the sample code to read the data from Database table Student(id,FirstName,LastName) using SQLDATAREADER
and bind it to the GridView .



ExDataReader.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExDataReader.aspx.cs" Inherits="ExDataReader" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >  


                 <Columns>  


                       <asp:BoundField DataField="Student_Id" HeaderText=" ID" />  


                       <asp:BoundField DataField="FirstName" HeaderText="First  Name" />  
                       
                       <asp:BoundField DataField="LastName" HeaderText="Last Name" />  


                   </Columns>  


                   <RowStyle HorizontalAlign="Center" />    
        </asp:GridView>
    </div>
    </form>
</body>
</html>

ExDataReader.aspx.cs


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class ExDataReader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


        SqlConnection Connobj = new SqlConnection();
        Connobj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        Connobj.Open();


        // Create a command object
        SqlCommand cmdGetStudent = new SqlCommand("select * from student", Connobj);


        // Create a data reader object.
        SqlDataReader dread;


        // Execute the command   
        dread = cmdGetStudent.ExecuteReader();


        GridView1.DataSource = dread;
        GridView1.DataBind();


        // Close the reader    
        dread.Close();
        // Close the database connection.   
        Connobj.Close(); 


    }
}



Below is the DotNetTrainingConnectionString in Web.config File


<add name="DotNetTrainingConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True"
   providerName="System.Data.SqlClient" />


Code Sample to Insert Data in Database using SqlDataAdapter

 have a Student table in DB (id (AutoIncrement),FirstName,LastName)

Below is the sample code to insert data using SqlDataAdapter object's Updae Method



AddItemsInDatabase.aspx 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddItemsInDatabase.aspx.cs" Inherits="AddItemsInDatabase" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
     <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br />
     
     <asp:Button ID="btnAdd" runat="server" Text="Button" onclick="btnAdd_Click" />
     
    
    </div>
   
    </form>
</body>
</html>


AddItemsInDatabase.aspx .cs


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;


public partial class AddItemsInDatabase : System.Web.UI.Page
{


    SqlConnection connObj = new SqlConnection();
    DataSet ds = new DataSet();
    SqlCommand objCommand;
    SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
        connObj.Open();


        
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        SqlCommand objCommand = new SqlCommand("Select * from student", connObj);


        objAdapter = new SqlDataAdapter(objCommand);


        objAdapter.Fill(ds);




        DataRow dr;
        dr = ds.Tables[0].NewRow();
        dr[1] = txtFirstName.Text;
        dr[2] = txtLastName.Text;


        ds.Tables[0].Rows.Add(dr);


        ds.Tables[0].TableName = "student";


        SqlCommand comm = new SqlCommand("insert into student(FirstName,LastName) values(@FirstName,@LastName)", connObj);






        comm.Parameters.Add("@LastName", SqlDbType.VarChar, 255, "LastName");
        comm.Parameters.Add("@FirstName", SqlDbType.VarChar, 255, "FirstName");




        objAdapter.InsertCommand = comm;
        objAdapter.Update(ds, "student");




    }
}

Below is the DotNetTrainingConnectionString in Web.config File


<add name="DotNetTrainingConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True"
   providerName="System.Data.SqlClient" />

Code Sample to Read Data From Database Using SqlDataAdapter and DataSet Object

Following is the sample code to read the data from Database table Student(id,FirstName,LastName)
and bind it to the GridView with paging implementation


Example10.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Example10.aspx.cs" Inherits="Example10" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <div>
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True"  PageSize ="2" OnPageIndexChanging="PageChange" >
        </asp:GridView>
        <asp:Button ID="btnAddRow" runat="server" Text="AddRow" OnClick="btnAddRow_Click" />&nbsp;
    </div>
    </div>
    </form>
</body>
</html>

Example10.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient ;


public partial class Example10 : System.Web.UI.Page
{
    SqlConnection connObj = new SqlConnection();
    DataSet ds = new DataSet();
    SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
            connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
            connObj.Open();




            SqlCommand objCommand = new SqlCommand("Select * from Country", connObj);
            objAdapter = new SqlDataAdapter(objCommand);


            objAdapter.Fill(ds);


            connObj.Close();


            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
           
    }
   


    public void PageChange(object sender, GridViewPageEventArgs e)
    {


        GridView1.PageIndex = e.NewPageIndex;
    }


    //private void Page_Error(object sender, System.EventArgs e)
    //{
    //    // Get the error.
    //    Exception ex = Server.GetLastError();
    //    Response.Write(ex.Message);




    //    //log Exception
    //    Trace.Warn("Error", "This is the exception Occured",ex);
    //    Trace.Write("Some Error Occured");


    //    // Store the message.
    //    Session["Error"] = ex.Message;


    //    // Clear the error.
    //    Server.ClearError();


    //    // Redisplay this page.
    //    //Response.Redirect("Example10.aspx");
    //}




}



Below is the DotNetTrainingConnectionString in Web.config File

<add name="DotNetTrainingConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True"
   providerName="System.Data.SqlClient" />


May 25, 2011

Insert Data in DB using ADO.NET

I have a Student table in DB (id (AutoIncrement),FirstName,LastName)

Below is the sample code to insert data using SqlCommand object's Execute Method

AddItemsInDatabase .aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddItemsInDatabase.aspx.cs" Inherits="AddItemsInDatabase" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
     <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br />
     
     <asp:Button ID="btnAdd" runat="server" Text="Button" onclick="btnAdd_Click" />
     
    
    </div>
   
    </form>
</body>
</html>

AddItemsInDatabase .aspx.cs


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;


public partial class AddItemsInDatabase : System.Web.UI.Page
{


    SqlConnection connObj = new SqlConnection();
    DataSet ds;
    SqlCommand objCommand;
    SqlDataAdapter objAdapter;
    protected void Page_Load(object sender, EventArgs e)
    {
        connObj.ConnectionString = ConfigurationManager.ConnectionStrings["DotNetTrainingConnectionString"].ToString();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {




        connObj.Open();
        SqlCommand comm = new SqlCommand("insert into student(FirstName,Lastname) values(@FirstName,@Lastname)", connObj);




        comm.Parameters.Add("@LastName", SqlDbType.VarChar, 255).Value = txtFirstName.Text;
        comm.Parameters.Add("@FirstName", SqlDbType.VarChar, 255).Value = txtLastName.Text;




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




    }
}

Below is the DotNetTrainingConnectionString in Web.config File


<add name="DotNetTrainingConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=DotNetTraining;Integrated Security=True"
   providerName="System.Data.SqlClient" />

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

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

I got the above error in the code bellow.
   
                Student_Marks e = (from e1 in DBobj.Student_Marks
                where e1.Student_Id == Convert.ToInt32(model.Student_Id)
                select e1).First();
                e.Marks = int.Parse(model.Marks);
                DBobj.SaveChanges();


 Note: model.Student_Id is string in the above code           

 If you use Convert.ToInt32(“ID”) in the Where clause the upper Exception is thrown.
Solution is to declare a variable of type int, which contains the converted value and use this variable in the Where query.


So I changed the code in the below manner and it worked.


         int StudentId = Convert.ToInt32(model.Student_Id);
         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();

Unable to update the EntitySet '' because it has a DefiningQuery and no element exists in the element to support the current operation

Unable to update the EntitySet '' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation

Got the above error when I was writing Code to insert data using EntityDataModel with below code


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




Solution : I rechecked Table Student_marks in Database and Primary Key was not
set in the table , I set the primary key and above problem was resolved

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