Is it possible to return anything else from controller apart from view? - asp.net-mvc

Is it possible to return a string from controller upon a form submission ?

[HttpPost]
public ActionResult Index()
{
return Content("some string", "text/plain");
}

You can, as Darin suggest, return Content(string);
There are also other possibilities such as
[HttpPost]
public ActionResult Index(FormCollection form) {
/*
return Json(json);
return View;
return PartialView;
*/
}
If you return something other than an action result it will automatically be wrapped in a ContentResult.
[HttpPost]
public ContentResult Index(FormCollection form) {
/*
return Content(string);
return File(bytes, contentType);
return DateTime.Now;
return 2;
*/
}

public ActionResult Index()
{
// ...
return File(bytes, contentType);
}

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

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/

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

Inconsistent accessibility: parameter type is less accessible

public class UserController : Controller
{
//
// GET: /User/
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User U)
{
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
dc.Users.Add(U);
dc.SaveChanges();
ModelState.Clear();
U = null;
ViewBag.Message = "Successfully register Done";
}
}
return View(U);
}
}
I suspect, but without the full error message giving us the type and location in the code it is something of a guess, that type User is protected or internal.

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