Monday 11 February 2013

Asp.net MVC View Page with HTML Tag Instead of HTML Helper

Let see how to create a MVC View Page with an normal HTML tag instead of Html Helper

Step 1: Create  a Database in Sql Server or Sql Express

Database Name: Contact Details
Table Name: Contact
Create Column:

       1.Id - Set Id to auto-increment
       2.Name - string
       3.Location - String

Step 2: Create a Asp.net MVC Application 4 Named  "Output"

1. Web.config - Add database connection

<connectionStrings> <add name="ContactDBContext" connectionString="Data Source=serverName;Initial Catalog=Contact Details; ID=sa;Password=**** providerName="System.Data.SqlClient" /> </connectionStrings>

2. Model:  Add ContactModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace Output.Models
{
    public class ContactModel
    {
       
        public int ID
        { get; set; }
        public string Name
        { get; set; }
        public string Location
        { get; set; }
       
    }
    public class ContactDBContext : DbContext
    {
        public DbSet<ContactModel> Contact { get; set; }
    }
}

3.Controller: Add ContactController

In Controller - Add view Name "Contact" and Call "ContactModel" and Make View as "Empty"

and add the folling content

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <form action="DisplayContact" method="post">

Name :- <input type="text" name="Name" /><br />
Location :-<input type="text" name="Location" /><br />
<input type="submit" value="Submit Contact Details" />
</form>
    </div>
</body>
</html>


4. In the ContactController add the following content


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Output.Models;

namespace Output.Controllers
{
    public class ContactController : Controller
    {
        ContactDBContext ContactDB = new ContactDBContext();
       
        //
        // GET: /Contact/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DisplayContact(string Name,string Location)
        {
            ContactModel obj = new ContactModel();
            obj.Name = Name;
            obj.Location = Location;
            ContactDB.Contact.Add(obj);
            ContactDB.SaveChanges();
            return RedirectToAction("Index");
           }
    }
}


That's it
Enjoy Coding....