put operations CRUD on a single file in asp.net - asp.net-mvc

**Hello
I am developing an application with ASP.NET API, i created the controller entity and the MVC controllers that my generated CRUD operations in the view as follows (see picture), each operation in a file how to put it all in a single file.
**
enter image description here
controller code:
// GET: /Clients/
public ActionResult Index()
{
return View(db.CLIENT.ToList());
}
// GET: /Clients/Details/5
public ActionResult Details(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Client_H Client_H = db.Client_H.Find(id);
if (Client_H == null)
{
return HttpNotFound();
}
return View(Client_H);
}
// GET: /Clients/Create
public ActionResult Create()
{
return View();
}
// POST: /Clients/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 ActionResult Create([Bind(Include="ID,nom,prenom,CODE,ADRESSE,BQE_VILLE,ADRESSE,TEL")] Client_H Client_H)
{
if (ModelState.IsValid)
{
db.Client_H.Add(Client_H);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Client_H);
}
// GET: /Clients/Edit/5
public ActionResult Edit(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Client_H Client_H = db.Client_H.Find(id);
if (Client_H == null)
{
return HttpNotFound();
}
return View(Client_H);
}
// POST: /Clients/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 ActionResult Edit([Bind(Include="ID,nom,prenom,CODE,ADRESSE,BQE_VILLE,ADRESSE,TEL")] Client_H Client_H)
{
if (ModelState.IsValid)
{
db.Entry(Client_H).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Client_H);
}
// GET: /Clients/Delete/5
public ActionResult Delete(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Client_H Client_H = db.Client_H.Find(id);
if (Client_H == null)
{
return HttpNotFound();
}
return View(Client_H);
}
// POST: /Clients/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(long id)
{
Client_H Client_H = db.Client_H.Find(id);
db.Client_H.Remove(Client_H);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
Thank you in advance

I do not understand well what do you mean by "how to put it all in a single file"?
If you want to have all CRUD function in on 1 view, you can use jquery POST & GET.
https://api.jquery.com/jquery.post/
https://api.jquery.com/jquery.get/

Related

Can't get action result to run if statement and go to logged in section

For some reason, The users in db.users.Where()is not working like the rest of the users in the code. Need some assistance to make it get to the logged in stage.
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User users)
{
if (ModelState.IsValid)
{
using(DataContext db = new DataContext())
{
var obj = db.users.Where(u => u.Username.Equals(users.Username) && u.Password.Equals(users.Password)).FirstOrDefault();
if (obj != null)
{
Session["UserID"] = obj.UserID.ToString();
Session["Username"] = obj.Username.ToString();
return RedirectToAction("LoggedIn");
}
}
}
return View(users);
}
public ActionResult LoggedIn()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}

Return Action as result of another action?

public ActionResult Index(int requestid)
{
return View(db.RequestListDetails.Where(c=>c.RequestID == requestid).ToList());
}
How can I back to View(db.RequestListDetails.Where(c=>c.RequestID == requestid).ToList()); from Create action.
My Create action code like this
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "....")] RequestListDetail requestListDetail)
{
if (ModelState.IsValid)
{
db.RequestListDetails.Add(requestListDetail);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(requestListDetail);
}
After db.SaveChanges() you could use this:
return RedirectToAction("Index", new { requestid = requestListDetail.RequestId });

How "Don't Repeat Yourself" in methods of a Controller in ASP.NET MVC?

within each methods of a controller , I have to execute a method.
public ActionResult Index1()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index1();
return View();
}
public ActionResult Index2()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index2();
return View();
}
public ActionResult Index3()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index3();
return View();
}
public ActionResult Index4()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index4();
return View();
}
Is there a smarter way than organize the code or I am forced to go against DRY concept?
I'd like not repeat the code for each method :
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Thanks to all.
Well, ASPNET has already the infrastructure for handling authorization so why not just use it?
Create a new attribute class, inherited from AuthorizeAttribute
Override the methods:
OnAuthorization: to perform your check
HandleUnauthorizedRequest: to decide whats the result view that the user will see.
Mark your controller methods with this attribute.
Your attribute may look like:
class MyCustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Do whatever you want here, for example
//filterContext.Result = new whatever() ;
base.HandleUnauthorizedRequest(filterContext);
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if ( /* the request does not pass your checks */ )
throw new UnauthorizedAccessException();
}
}
And your controller code will look like:
[MyCustomAuthorize]
public ActionResult Index1()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index2()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index3()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index4()
{
return View();
}
You can also check this post for a more clear example:
https://stackoverflow.com/a/5663518/1413973
You can refactor your controller like this:
public ActionResult Index1()
{
return AccessDeniedRedirect();
}
public ActionResult Index2()
{
return AccessDeniedRedirect();
}
public ActionResult Index3()
{
return AccessDeniedRedirect();
}
public ActionResult Index4()
{
return AccessDeniedRedirect();
}
private ActionResult AccessDeniedRedirect()
{
if (Checks(id, SessionManage.DataSession))
return RedirectToAction("AccesDiened");
return View();
}

CRUD in MVC repository

I have created a repository data layer in my MVC web application, and want to use it for my CRUD methods. But I came to think of situations where I want to do something like:
If record does not exist
create record
else
update record
But how does this fit into CRUD? Is this two-in-one operation logic supposed to be kept in the controller?
I think the repository should take care of that, the controller should be as light as possible:
At repository level:
public bool CreateUpdate(Type model)
{
var record = db.FirstOrDefault(x=> x.Id == model.Id);
if(record == null)
{
Create(model);
}
else
{
Update(model);
}
}
public bool Create(Type model)
{
//create logic here
}
public bool Update(Type model)
{
//update logic here
}
This can be done with this code
var data = db.tableName.where(x=> x.Id == model.Id).FirstOrDefault();
if(data== null)
{
db.FAQCategories.Add(model);
db.SaveChanges();
}
else
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
}
public IActionResult Create()
{
return View();
}
// POST: AdminPanel/Students/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Student student)
{
if (!ModelState.IsValid)
{
return View();
}
student.Image = await student.Photo.SaveFileAsync(_environment.WebRootPath, "images");
await _context.Students.AddAsync(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
// GET: AdminPanel/Students/Edit/5
public async Task<IActionResult> Update(int? id)
{
if (id == null)
{
return BadRequest();
}
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return NotFound();
}
return View(student);
}
// POST: AdminPanel/Students/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Update(int? id, Student newstudent)
{
if (id==null)
{
return BadRequest();
}
var oldstudent = _context.Students.Find(id);
if (oldstudent == null)
{
return NotFound();
}
if (!ModelState.IsValid)
{
return View();
}
var path = Helper.GetPath(_environment.WebRootPath, "images", oldstudent.Image);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
newstudent.Image = await newstudent.Photo.SaveFileAsync(_env.WebRootPath, "images");
oldstudent.Image = newstudent.Image;
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Delete(int id)
{
if (id == null)
{
return BadRequest();
}
var student= _context.Students.Find(id);
if (student== null)
{
return NotFound();
}
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}

Delete Method based on condition in MVC 4

I have created an application in MVC 4 using Razor HTML. I have set up a model that has a few properties and my delete method which is posted below. This method works perfectly except for the fact that I don't want it to allow me to delete anything if one of the properties is not a certain number. How can i implement that in this method?
public ActionResult Delete(int id = 0)
{
Material material = db.Materials.Find(id);
if(material == null)
{
return HttpNotFound();
}
return View(material);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Material material = db.Materials.Find(id);
db.Materials.Remove(material);
db.SaveChanges();
return RedirecttoAction("Index");
}
In both your get and post actions, check the property and return an alternate "no delete allowed" view if the property you are checking doesn't have an allowable value.
public ActionResult Delete(int id = 0)
{
Material material = db.Materials.Find(id);
if(material == null)
{
return HttpNotFound();
}
else if (material.CheckedProperty != AllowableValue)
{
return View("DeleteNotAllowed", material);
}
return View(material);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Material material = db.Materials.Find(id);
if (material.CheckedProperty != AllowableValue)
{
return View("DeleteNotAllowed", material);
}
db.Materials.Remove(material);
db.SaveChanges();
return RedirecttoAction("Index");
}

Resources