
MODELS
[1] CREATE USER MODEL
-----------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace _1___kushan.Models
{
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
}
[2] CREATE DB CONTEXT
---------------------
namespace _1___kushan.Models
{
public class Context : DbContext
{
public DbSet<Models.User> Users { get; set; }
}
}
CONTROLLER
[3] CREATE CONTROLLER
---------------------
using _1___kushan.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace _1___kushan.Controllers
{
public class UserController : Controller
{
//
// GET: /User/
public ActionResult Index()
{
return View();
}
//RESPONSE FOR SIMPLE BUTTON CLICK
[HttpPost]
public ActionResult Index(Models.User user)
{
Context con = new Context();//object with context
User u = new User//user model
{
Name = user.Name
};
con.Users.Add(u);//adding
con.SaveChanges();//writes to DB
return View();
}
}
}
VIEW
[4] GENERATE THE VIEW USING SCAFFOLDING
-----------------------------------------------------
@model _1___kushan.Models.User
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Index","User")) { <%--mention action & controller --%>
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Comments
Post a Comment