Delete Method based on condition in MVC 4 - asp.net-mvc

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");
}

Related

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 });

Edit is Adding database record - not updating the record

I had this code working - then I added the ability to add or update an image from the edit function - not when I add an image and try to update the sql record - it adds a new record. Here is the controller code for the edit. ANy ideas?
public ActionResult Edit(int id)
{
var Emp = db.Employees.Find(id);
if (Emp == null)
{
return HttpNotFound();
}
return View(Emp);
}
// POST: Employees/Edit/5
[HttpPost]
public ActionResult Edit(int id, Employee employee, HttpPostedFileBase image1)
{
try
{
if (image1 != null)
{
employee.Image = new byte[image1.ContentLength];
image1.InputStream.Read(employee.Image, 0, image1.ContentLength);
}
db.Entry(employee).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = id });
}
catch
{
return View();
}
}

put operations CRUD on a single file in asp.net

**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/

Using ViewModels in asp.net mvc 3

Here is my scenario: (These all have to accomplished in the same view as an accepted requirement)
User enters a few search criterias to search users.
Page lists the search results with an update link besides.
User clicks on one of the update links and a form appears to enable editing the data.
User does changes and saves the data that binded to form.
I used a view model for this view. Here it is.
[Serializable]
public class UserAddModel
{
public UserSearchCriteria UserSearchCriteria { get; set; }
public UserEntity User { get; set; }
public List<UserPrincipalDto> SearchResults { get; set; }
}
And here is my controller:
using System;
namespace x.Web.BackOffice.Controllers
{
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
[Authorize(Roles = "Admin")]
public class UserController : Controller
{
private readonly IAuthentication _authentication;
private readonly List<RoleEntity> roles = new Y.Framework.Data.Repository<RoleEntity>().Get(null).ToList();
private Repository<UserEntity> repository = new Repository<UserEntity>();
[ImportingConstructor]
public UserController(IAuthentication authentication)
{
this._authentication = authentication;
}
public ActionResult Index()
{
return View(new UserAddModel());
}
[HttpPost]
public ActionResult GetSearchResults(UserAddModel model)
{
if (ModelState.IsValid)
{
try
{
List<UserPrincipalDto> results =
_authentication.SearchUsers(
ConfigurationManager.AppSettings["DomainName"],
model.UserSearchCriteria.FirstName,
model.UserSearchCriteria.LastName,
model.UserSearchCriteria.Username);
model.SearchResults = results;
Session["UserAddModel"] = model;
return View("Index", model);
}
catch (Exception ex)
{
Logger.Log(ex, User.Identity.Name);
}
}
else
{
ModelState.AddModelError("", "Error!");
}
Session["UserAddModel"] = model;
return View("Index", model);
}
public ActionResult Save(string username)
{
UserAddModel model = Session["UserAddModel"] as UserAddModel;
UserEntity exists = repository.Get(u => u.Username == username).FirstOrDefault();
if (exists == null)
{
UserPrincipal userPrincipal =
_authentication.GetUserDetails(
ConfigurationManager.AppSettings["DomainName"],
username);
model.User = new UserEntity();
model.User.Id = userPrincipal.Guid.Value;
model.User.FirstName = userPrincipal.DisplayName.FullNameToFirstName();
model.User.LastName = userPrincipal.DisplayName.FullNameToLastName();
model.User.Email = userPrincipal.EmailAddress;
model.User.Username = userPrincipal.SamAccountName;
}
else
{
model.User = new UserEntity();
model.User.Id = exists.Id;
model.User.FirstName = exists.FirstName;
model.User.LastName = exists.LastName;
model.User.Email = exists.Email;
model.User.Username = exists.Username;
model.User.RoleId = exists.RoleId;
}
ViewBag.Roles = roles;
return View("Index", model);
}
[HttpPost]
public ActionResult Save(UserAddModel model)
{
UserEntity exists = repository.Get(u => u.Id == model.User.Id).FirstOrDefault();
if (exists == null)
{
Result result = repository.Save(model.User);
HandleResult(result, model);
}
else
{
Result result = repository.Save(model.User, PageMode.Edit);
HandleResult(result, model);
}
ViewBag.Roles = roles;
return View("Index", model);
}
}
}
As you see there are two different forms in my view and I'm storing the whole view model in Session in my controller. But I think this is not fine enough. What if session expires or what if I have to deploy my application using a load balancer?
What is the best way to develop this kind of page? I'm open to any kind of suggestions.
Thanks in advance,

Delete Not working in MVC 2

// GET: /Product/Delete/5
public ActionResult Delete(int id)
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
//return View(data.Products.FirstOrDefault(p => p.ProductID == id));
return View(res);
}
//
// POST: /Product/Delete/5
// [HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
**public ActionResult Delete(Product producttodelete)**
{
try
{
// TODO: Add delete logic here
var res = (from r in data.Products where r.ProductID == producttodelete.ProductID select r).FirstOrDefault();
// var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
Here in the line "producttodelete" i am not getting any values it is cuming null.Rather than create,details,edit are working fine.... only delete not working.......I tried a lot
Assuming you are using strongly typed views, have you tried:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, Product productToDelete)
{
try
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
... or if you are not using strongly typed views:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
In either case, you need to provide an id parameter which you can then use to get your object from your datastore. The default route mapping in MVC2 (in Global.asax.cs) will take the ID from the post URL and map it to this parameter for you.
why not just get the id like you were in the rest instead of trying to get the whole model? it seems like you're just selecting using the id anyway. try this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
try
{
// TODO: Add delete logic here
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
// var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}

Resources