CRUD operations in MVC 3 without using db context - c#

I need help .Actually am using ADO net with 4.0 .net framework and create a own database using app_data in solution explorer with .mdf extension.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Crudoperations.Models;
using System.Data.Entity;
namespace Crudoperations.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
EmployEntities employContext;
public ActionResult Index()
{
using (var details= new EmployEntities())
{
return View(details.employs.ToList());
}
}
//
// GET: /Employee/Details/5
public ActionResult Details(int id)
{
employContext = new EmployEntities();
employ _TempEmploy = new employ();
_TempEmploy.Id = id;
return View(_TempEmploy);
}
//
// GET: /Employee/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(employ objEmploy)
{
try
{
employContext = new EmployEntities();
employContext.AddToemploys(objEmploy);
employContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
employContext = new EmployEntities();
employ _employ = new employ();
//_employ = ( from Employ
// where ID = id)
return View();
}
[HttpPost]
public ActionResult Edit(int id, employ objEmploy)
{
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Employee/Delete/5
public ActionResult Delete(int id)
{
employ _TempEmploy = new employ();
return View(_TempEmploy);
}
//
// POST: /Employee/Delete/5
[HttpPost]
public ActionResult Delete(int id, employ objEmploy)
{
try
{
//employContext = new EmployEntities();
//employ _TempEmploy = new employ();
//_TempEmploy.Id = id;
//employ _employ = employContext.Find(_TempEmploy);
employContext.DeleteObject(objEmploy);
employContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
public IView detailsModel { get; set; }
}
}
Actually i'm getting problem in accessing the data using ID i.e in db context there is a method "Find(id)" but there is no such type of method in Object context.what i have to do for accessing the data for edit ,details and Delete the data from database

you can use FirstOrDefault() for fetching by id, It will fetch the first matching object.
db.Users.FirstOrDefault(x => x.UserId== Id);
Hope, it may help you. Have anice day.

Related

View in areas cannot be located - Visual Studio 2015, C#, ASP.NET MVC 5

I've found many topic and suggestions on this and I think I've tried all of the combinations.
I had a working application that is going to grow larger so I decided to make use of areas. I sloughed through that and can access the controllers but then the application fails when it tries to return data to a view. I created a test data context, classes, etc. then to be sure that it wasn't something that I did wrong when moving into areas.
It's probably best to work through the somewhat smaller test situation and then apply what works to the larger actual application.
My link from _Layout.cshtml:
<li>#Html.ActionLink("Test", "Index", "testclasses")</li>
My model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Tracking.Areas.test.Models
{
public class testclass
{
public int ID { get; set; }
}
}
My testAreaRegistration:
using System.Web.Mvc;
namespace Tracking.Areas.test
{
public class testAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "test";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"test_default",
//"test/{controller}/{action}/{id}",
"test/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}
My test controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tracking.Areas.test.Models;
using Tracking.DAL.Test;
namespace Tracking.Areas.test.Controllers
{
[RouteArea("test")]
public class testclassesController : Controller
{
private testcontext db = new testcontext();
// GET: test/testclasses
public async Task<ActionResult> Index()
{
return View(await db.spas.ToListAsync());
}
// GET: test/testclasses/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
testclass testclass = await db.spas.FindAsync(id);
if (testclass == null)
{
return HttpNotFound();
}
return View(testclass);
}
// GET: test/testclasses/Create
public ActionResult Create()
{
return View();
}
// POST: test/testclasses/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ID")] testclass testclass)
{
if (ModelState.IsValid)
{
db.spas.Add(testclass);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(testclass);
}
// GET: test/testclasses/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
testclass testclass = await db.spas.FindAsync(id);
if (testclass == null)
{
return HttpNotFound();
}
return View(testclass);
}
// POST: test/testclasses/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID")] testclass testclass)
{
if (ModelState.IsValid)
{
db.Entry(testclass).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(testclass);
}
// GET: test/testclasses/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
testclass testclass = await db.spas.FindAsync(id);
if (testclass == null)
{
return HttpNotFound();
}
return View(testclass);
}
// POST: test/testclasses/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
testclass testclass = await db.spas.FindAsync(id);
db.spas.Remove(testclass);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My RouteConfig file
namespace Tracking
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
My Global.asax.cs file
namespace Tracking
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
I've tried with and without [RouteArea("test")] in the controller; I've tried multiple options with adding a controller to the area registration file, removing the area name from in front of controller in the area registration file, and many other combinations.
The code finds the controller and model as I put breakpoints in those and reach them - when it attempts to return the view I get the error message about the index view not being found in the standard locations - it doesn't search within the areas at all.
Thanks!
I think you have an inconsistence in your "convention over configuration" setup. Might be helpful to add the error message and your solution structure. You should check, for example, that the Index.cshtml is found in the Areas\test\Views\testclasses folder. The only thing that I see at a first glance is that you didn't modify your action link to include the area. You should try:
#Html.ActionLink("Test", "Index", "testclasses", new { Area = "test" }, new{})
P.S.> I would recommend using camel case notation for the class names and areas... you know, for the clean code sake. Not to mention that you never know when you might stumble upon a case sensitive convention....

CS1503 Argument 1: cannot convert from 'Employee.Controllers.EmployeController' to 'Employee.Table' Employe

namespace Employee.Controllers
{
public class EmployeController : Controller
{
EmployeeEntities db = new EmployeeEntities();
// GET: Employe
public ActionResult Index()
{
return View(db.Tables.ToList());
}
// GET: Add Employee
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
// POST
public ActionResult Create(EmployeController employe)
{
if(ModelState.IsValid)
{
db.Tables.Add(employe);
}
return View(employe);
}
I think your problem is obvious. You mistakenly pass EmployeController employe in your action Create (post). Change it with your actual model.

cs0029 cannot implicitly convert type 'ApplicationUser' to 'User'

I am creating an app with register and authentication.
I was using this article exactly as in there. https://azure.microsoft.com/en-gb/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/
I get errors after creating controllers as in the article, before enabling migrations. Of course I can't enable migrations cause lots of errors. What could I do?
I searched for answers but mostly it is 'string' to 'int' or something similar.
Full Error: CS0029 C# Cannot implicitly convert type 'PingGod.Models.ApplicationUser' to 'PingGod.Models.User'
Also I get some other error but probably the same meaning just other way around: CS1503 C# Argument 1: cannot convert from 'PingGod.Models.User' to 'PingGod.Models.ApplicationUser'
Thanks for your help in advance!
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PingGod.Models;
namespace PingGod.Controllers
{
public class UsersController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: Users
public ActionResult Index()
{
return View(db.Users.ToList());
}
// GET: Users/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Users users = db.Users.Find(id); //Here I get error (CS0029)
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
// GET: Users/Create
public ActionResult Create()
{
return View();
}
// POST: Users/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UserId,Name,Address,City,State,Zip,Email,url")] Users users)
{
if (ModelState.IsValid)
{
db.Users.Add(users); //Here an error also (CS1503)
db.SaveChanges();
return RedirectToAction("Index");
}
return View(users);
}
// GET: Users/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Users users = db.Users.Find(id); //Here error (CS0029)
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
// POST: Users/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "UserId,Name,Address,City,State,Zip,Email,url")] Users users)
{
if (ModelState.IsValid)
{
db.Entry(users).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(users);
}
// GET: Users/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Users users = db.Users.Find(id); //Here eror (CS0029)
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
// POST: Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Users users = db.Users.Find(id); // Here also an error (CS0029)
db.Users.Remove(users); //Here other error (CS1503)
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Both Users Class are different, that's why you got this error
Use
PingGod.Models.Users users = db.Users.Find(id)
Maybe this helps u

What is the best way to update only some fields of an object in MVC?

I am trying to update a news post. The post has a date field called Created that is populated when the record is initially created. I don't include this when updating, so when using the below method, this is null and throws an error.
I am using MVC 5 and Entity Framework 6
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Summary,Content")] Post post) {
if (ModelState.IsValid) {
db.Entry(post).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
This method does work but it seems a bit clunky.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Summary,Content")] Post post) {
if (ModelState.IsValid) {
var newsPost = db.Posts.Find(post.Id);
if (newsPost == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); }
newsPost.Title = post.Title;
newsPost.Summary = post.Summary;
newsPost.Content = post.Content;
db.Entry(newsPost).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
What is the best practice method of doing this?
Thanks!
EF also has a simple built-in "AutoMapper" that works with scalar values.
public class PostViewModel()
{
public string Id {get;set;}
public string Title {get;set;}
public string Summary {get;set;}
public string Content {get;set;}
}
public ActionResult Edit(PostViewModel viewModel)
{
if (ModelState.IsValid) {
var newsPost = db.Posts.Find(post.Id);
...
db.Entry(newsPost).CurrentValues.SetValues(viewModel);
...
}
}
I use a repository method. Works really well.
It copies the column which are different. Sort of PATCH against PUT
public void CopyUpdate<T> (T modelorig, T model) where T : class
{
_context.Entry(model).CurrentValues.SetValues(modelorig);
_context.Set<T>().Add(model);
_context.Entry(model).State = EntityState.Modified;
_context.SaveChanges();
}
The "correct" way to do this, assuming you want to stick to Rest. Is to use HttpPatch.
https://learn.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-6.0
[HttpPatch]
[ValidateAntiForgeryToken]
public async Task<ActionResult> PatchAsync([FromBody] JsonPatchDocument<Post> patchDoc, int id) {
var post = db.Find(id);
patchDoc.ApplyTo(post, ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await db.SaveChangesAsync();
return new ObjectResult(post);
}

The resource cannot be found MVC 4

I'm working on Visual Studio, MVC.
I generated an ADO model, created a new controller with this model and changed the route but my controller seem inusable, even if i try to redirect from another controller.
My controller :
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Garnak.Models;
namespace Garnak.Views
{
public class leIndex : Controller
{
private garnakEntities db = new garnakEntities();
//
// GET: /leIndex/
public ActionResult Index()
{
return View(db.compteSet.ToList());
}
//
// GET: /leIndex/Details/5
public ActionResult Details(int id = 0)
{
compteSet compteset = db.compteSet.Find(id);
if (compteset == null)
{
return HttpNotFound();
}
return View(compteset);
}
//
// GET: /leIndex/Create
public ActionResult Create()
{
return View();
}
//
// POST: /leIndex/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(compteSet compteset)
{
if (ModelState.IsValid)
{
db.compteSet.Add(compteset);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(compteset);
}
//
// GET: /leIndex/Edit/5
public ActionResult Edit(int id = 0)
{
compteSet compteset = db.compteSet.Find(id);
if (compteset == null)
{
return HttpNotFound();
}
return View(compteset);
}
//
// POST: /leIndex/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(compteSet compteset)
{
if (ModelState.IsValid)
{
db.Entry(compteset).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(compteset);
}
//
// GET: /leIndex/Delete/5
public ActionResult Delete(int id = 0)
{
compteSet compteset = db.compteSet.Find(id);
if (compteset == null)
{
return HttpNotFound();
}
return View(compteset);
}
//
// POST: /leIndex/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
compteSet compteset = db.compteSet.Find(id);
db.compteSet.Remove(compteset);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
My route :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Garnak
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "leIndex", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Any idea why Visual studio say me that the ressource cannot be found ?
ASP.NET MVC's controller factory, follows a naming convention that your controllers should follow it -by default. You can change it by creating your own factory, but for now, change
public class leIndex : Controller { ... }
to
public class leIndexController : Controller { ... }

Categories

Resources