You can see the older data in
var data = context.DEMO_MAST.Where(x => x.ID == model.ID).FirstOrDefault();
and new data in Model and just using If Condition you can do AddEdit both things in single method.
AddEdit Method
public int AddOrEdit(DEMO_MAST model)
{
try
{
var data = context.DEMO_MAST.Where(x => x.ID == model.ID).FirstOrDefault();
if (data == null)
{
model.CREATED_ON = DateTime.Now;
this.context.DEMO_MAST.Add(model);
}
else
{
model.MODIFIED_ON = DateTime.Now;
this.context.Entry(data).CurrentValues.SetValues(model);
}
int flg = this.context.SaveChanges();
return flg;
}
catch (Exception ex)
{
return 0;
}
}
Find
public DEMO_MAST Find(int ID)
{
return context.DEMO_MAST.where(x=>x.ID==ID).FirstorDefault();
}
Controller
[HttpGet]
public ActionResult Index(int ID)
{
DEMO_MAST model=new DEMO_MAST();
if(ID>0)
{
model=Find(ID);
}
return View(model);
}
[HttpPost]
public ActionResult Index(DEMO_MAST model)
{
if(ModelState.IsValid)
{
int i = AddEdit(model);
if(i>0)
{
ViewBag.Message="Record AddEdit Successfully";
}
else
{
ViewBag.Message="Error";
}
}
return View(model);
}
So when you run your application simple Index() view is display.
Index view for get data
using (Html.BeginForm("Index", "Home"))
{
<div class="row">
<div class="col-md-6 col-sm-3">
</div>
<div class="col-md-6 col-sm-9">
<div id="sample_6_filter" class="dataTables_filter">
<label>
@Html.TextBox("ID", ViewBag.ID == null ? "" : (string)ViewBag.ID, new { @class = "form-control input-inline", placeholder = "ID" })
<button class="btn green-haze" type="submit" id="submit">
<i class="fa fa-search"></i>
</button>
</label>
</div>
</div>
</div>
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.HiddenFor(x => x.ID)
@Html.HiddenFor(x => x.CREATED_ON)
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-4">Name</label>
<div class="col-sm-5">
@Html.TextBoxFor(a => a.Name, new { @class = "form-control", @maxlength = "50" })
</div>
<div class="col-sm-3 text-danger">
</div>
</div>
<div class="form-group">
<div class="col-sm-12 text-center">
<button type="submit" name="command" value="createUser" class="btn btn-lg btn-green hvr-underline-from-center">Submit</button>
</div>
</div>
}
You need to enter ID or any Uniq field of your database for get result in View.
When you click on button the [HttpGet] Index method will be called and display records in view.
And after that you can modify your data.Click on submit so it will go for
'[HttPost] Index' remain things done automatically as per above code and methods.
Now you just need to set your data in view.. that's it.
Hope you understand!! Enjoy!!
Session)index()for get andindex(Model model)for post. so when you submit your form ID will passed with model and you can edit that perticular record using single view..