Redirect to same view - asp.net-mvc

I am working on a ASP.NET MVC website and I am new to this.
I have a controller with few actions. I want to use these actions through out my website.
For example
[HttpPost]
public ActionResult MyAction(ViewModel model)
{
if (ModelState.IsValid)
{
//code is here
}
return RedirectToAction(); // redirect to same view
}
I want to redirect to same view from where request is generated. I am not sure if this is possible or not ?

Based on your comment, I would create a Controller that looks like:
public MyController : Controller
{
private ActionResult SharedMethod(SomeModel model)
{
if (ModelState.IsValid)
{
//code is here
}
// viewname is required, otherwise the view name used will be
// the original calling method (ie public1.cshtml, public2.cshtml)
return this.View("SharedViewName");
}
public ActionResult Public1(SomeModel model)
{
return this.SharedMethod(model);
}
public ActionResult Public1(SomeModel model)
{
return this.SharedMethod(model);
}
}

Related

Generic class to identify Current Session information in ASP.Net MVC application

I'm developing a simple Custom Role-based Web Application using ASP.Net MVC, In my login Action, I'm creating a Profile session as below:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
using (HostingEnvironment.Impersonate())
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
var employeeProfile = AccountBal.Instance.GetEmployee(loginId);
Session["Profile"] = employeeProfile;
FormsAuthentication.SetAuthCookie(model.UserName, true);
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", #"The user name or password provided is incorrect.");
return View(model);
}
}
And I'm checking this or using this session in all Controller Actions as below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(MyModel model)
{
var employee = (Employee) Session["Profile"];
if (employee == null)
return RedirectToAction("Login", "Account");
if (ModelState.IsValid)
{
// Functionality goes here....
}
}
Is there any way I can move this piece of session checking code in a base class or centralized class? so that, I do not need to check it every time in a Controller Actions instead I will access the properties directly
say,
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateOrEdit(MyModel model)
{
var employee = _profileBase.GetCurrentProfile();
if (employee == null)
return RedirectToAction("Login", "Account");
if (ModelState.IsValid)
{
// Functionality goes here....
}
}
Create a base controller that contains your GetCurrentProfile method to retrieve current user profile like
public class BaseController : Controller
{
public Employee GetCurrentProfile()
{
return (Employee)Session["Profile"];
}
public bool SetCurrentProfile(Employee emp)
{
Session["Profile"] = emp;
return true;
}
}
And inherit your desired controller with above BaseController and access your GetCurrentProfile method like below
public class HomeController : BaseController
{
public ActionResult SetProfile()
{
var emp = new Employee { ID = 1, Name = "Abc", Mobile = "123" };
//Set your profile here
if (SetCurrentProfile(emp))
{
//Do code after set employee profile
}
return View();
}
public ActionResult GetProfile()
{
//Get your profile here
var employee = GetCurrentProfile();
return View();
}
}
GetCurrentProfile and SetCurrentProfile directly available to your desired controller because we directly inherit it from BaseController.
You may usetry/catch in above code snippet.
Try once may it help you

How To call An Action In Umbraco Controller?

I created an Umbraco DocumentType with the alias Personal and created a controller that inherits
Umbraco.Web.Mvc.RenderMvcController
I added two Actions, one is the default action and the other is called Test.
How can I fire the Test Action from the Personal controller?
public class PersonalController : Umbraco.Web.Mvc.RenderMvcController
{
// GET: Personal
public override ActionResult Index(RenderModel model)
{
return base.Index(model);
}
public String Test(RenderModel model)
{
return "fff";
}
}
When I put the url like this: localHost/personal/test it shows:
No umbraco document matches the url '/test'.
Which is right, so how can I call it?
I would do it like this
[HttpPost]
public ActionResult SubmitSearchForm(SearchViewModel model)
{
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(model.SearchTerm))
{
model.SearchTerm = model.SearchTerm;
model.SearchGroups = GetSearchGroups(model);
model.SearchResults = _searchHelper.GetSearchResults(model, Request.Form.AllKeys);
}
return RenderSearchResults(model.SearchResults);
}
return null;
}
public ActionResult RenderSearchResults(SearchResultsModel model)
{
return PartialView(PartialViewPath("_SearchResults"), model);
}
See this blog post for the full context behind where this code snippet came from.
http://www.codeshare.co.uk/blog/how-to-search-by-document-type-and-property-in-umbraco/

Asp.Net Mvc Multiple Attribute Routing

I have a controller (CarsController).
I want to set multiple route to action in this controller. For example;
public class CarsController : Controller
{
[Route("cars/create")]
[Route("cars/edit/{id}")]
public action CreateOrEdit(int? id)
{
...
}
}
But I can not. What's the problem?
Following code is great work. Thank You Tetsuya Yamamoto..
[Route("cars/{type:regex(create|edit)}/{id?}")]
public async Task<ActionResult> CreateOrEdit(long? id)
{
await FillViewBag();
if (id.HasValue)
{
return View(await this.Database.Cars.Include(i => i.Files).SingleAsync(id.Value));
}
return View();
}
When using in action
#Url.Action("CreateOrEdit", new { type="create"})

Redirect from a [HttpGet] Action To [HttpPost] Action - MVC3

I want to redirect to a [HttpPost] Action from a [HttpGet] Action in the same controller.
Is it possible?
I'm trying to not rewrite the same code for a Login, because it is a complex, and not typical logon function
This is my code:
[HttpGet]
public ActionResult Login(){
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//search user and create sesion
//...
if (registered)
{
return this.RedirectToAction("Home","Index");
}else{
return this.RedirectToAction("Home", "signIn");
}
}
[HttpGet]
public ActionResult signIn(){
return View();
}
[HttpGet]
public ActionResult signInUserModel model)
{
//Register new User
//...
if (allOk)
{
LoginModel loginModel = new LoginModel();
loginModel.User = model.User;
loginModel.password = model.password;
//next line doesn't work!!!!!
return this.RedirectToAction("Home","Login", new { model = loginModel);
}else{
//error
//...
}
}
Any help would be appreciated.
Thanks
You can return a different View from the method name
public ActionResult signInUserModel model)
{
...
return View("Login", loginModel);
}
Bit late, but I just had the same issue...
You could refactor the core login logic out from the Post method and then call that new method from both places.
e.g. Suppose you create a LoginService class to handle logging someone in. It's just a case of using that from both your actions, so no need to redirect from one action to the other
It is possible. All actions must be in the same controller.
public ActionResult Login(){
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//search user and create sesion
//...
if (registered)
{
return RedirectToAction("Index");
}
return View(model);
}
public ActionResult SignIn(){
return View();
}
[HttpPost]
public ActionResult SignIn(UserModel model)
{
//Register new User
//...
if (allOk)
{
return RedirectToAction("Login");
}
return View(model);
}

C# ASP.NET MVC: Find out whether GET or POST was invoked on controller action

How do I find out whether a GET or a POST hit my ASP.NET MVC controller action?
You can check Request.HttpMethod for that.
if (Request.HttpMethod == "POST") {
//the controller was hit with POST
}
else {
//etc.
}
You can separate your controller methods:
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Operation()
{
// insert here the GET logic
return SomeView(...)
}
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Operation(SomeModel model)
{
// insert here the POST logic
return SomeView(...);
}
You can also use the ActionResults For Get and Post methods separately as below:
[HttpGet]
public ActionResult Operation()
{
return View(...)
}
[HttpPost]
public ActionResult Operation(SomeModel model)
{
return View(...);
}

Resources