Renderaction refresh / redirect parent page - asp.net-mvc-3

I am currently working on an asp.net 4 mvc application and I'm trying to work out the best way to redirect / refresh the parent page after a form is submitted in the child controller.
So in my main view I have
Main View
#Html.RenderAction("child")
Child View / Controller
[HttpPost]
public ActionResult Create() {
if (ModelState.IsValid) {
// Save
Save();
Response.Redirect(Request.Url.ToString()); <--- Redirects the main page hack
}
return PartialView();
}
What is the correct way to redirect / refresh the main page hosting the renderaction?
DotnetShadow

just check how the default Account controller (Internet Application template) has this set for the Login/LogOff actions :
public ActionResult LogOff()
{
(...)
return RedirectToAction("Index", "Home");
}

Related

static content pages in an MVC web application

I have just created my first MVC 3 project for a database search using EF db first, but the search is only a part of a big website most of the pages will just contain some text and images.
My question is basically about these pages which on the website would be .aspx, and the code behind would have nothing at all.
They use a master page and some user controls - my guess is that's the reason our front end person made them aspx not html.
I need to convert/include her pages into my project (I don't want to go back to stored procedures and listview after having used EF and Linq, plus I don't have time).
I know of one possible way: create a controller for each of the main menu items, then add ActionResult named for each of the submenu items returning View(), then create respective views.
public class LearnAboutStandardsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ITSStandardsBackground()
{
return View();
}
public ActionResult ResearchInitiatives()
{
return View();
}
So my static content pages will become Views.
It's working, I just want to do it for the rest of the pages and modify the links in the text of these pages.
Is there any other way to handle these pages?
There is no logic behind these pages.
I know this was not a perfect project for the MVC pattern with so much static content, but I had my reasons for it.
I handle this with an "StaticContent" controller:
StaticContentController.cs
public class StaticContentController : Controller
{
public ActionResult About()
{
return View();
}
public ActionResult Services()
{
return View();
}
public ActionResult Portfolio()
{
return View();
}
}
Add the code below your route config to handle the static routes:
routes.MapRoute(
"StaticContent",
"{action}",
new { controller = "StaticContent" },
new { action = "About|Services|Portfolio" } // Add more here
);
You're set.
If you need more pages just add the action in the StaticController and adjust your StaticContent MapRoute.
Personally, I would have controllers with simple actions that just render views. That way if you do add more features later you're already set up. And if you want to add security or caching it's a lot easier and more consistent.
You can still use WebForms (with the new Friendly URLs feature if you want "pretty" URLs) for the "static" pages. Or you can use Web Pages with Razor and create CSHTML files for the static content.

How to redirect from one view to another view in MVC3?

Hello everyone I would like to ask how to redirect from one view to another. Here is my view
#model IEnumerable<test.Models.contents>
#using test
#if(Request.IsAuthenticated) {
<text>Welcome<strong>#User.Identity.Name</strong>
</text>
}
else
{
???
}
Don't do any redirects inside the view. That's not its responsibility. The responsibility of a view is to display data that is passed to it from the controller action under the form of a view model.
Do this redirect inside the controller action that is rendering this view. For example you could decorate it with the [Authorize] attribute. This way if the user is not authorized he will be redirected to the loginUrl you specified in your web.config:
[Authorize]
public ActionResult SomeAction()
{
return View();
}
and if you wanted to redirect to some particular view you could simply write a custom Authorize attribute and override the HandleUnauthorizedRequest method to specify the controller and action you wish to redirect to in case of user not being authenticated:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var values = new RouteValueDictionary(new
{
controller = "SomeController",
action = "NotAuthorized"
});
filterContext.Result = new RedirectToRouteResult(values);
}
}
and then decorate your action with it:
[MyAuthorize]
public ActionResult SomeAction()
{
return View();
}
Now inside the corresponding view you don't need to perform any tests. It is guaranteed that if you got as far as rendering this view the user is authenticated and you could welcome him directly:
#model IEnumerable<test.Models.contents>
#using test
Welcome <strong>#User.Identity.Name</strong>

FormsAuthentication.SignOut() does not want to redirect to logout view

I am trying to redirect to a logout view when the user clicks on logout but mvc intercepts the redirection.
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Logout", "Account");
}
public ActionResult Logout()
{
return View("LogOff");
}
Id like the LogOff view to be displayed after logout
I guess you have marked the complete account controller with the Authorize attribute. You should decorate only the actions that required authorization with that.

How do I perform error handling in ASP.NET MVC 3 controller?

I have an Account controller which have:
LoginForm (get action)
Login (post action)
RegisterForm (get action)
Register (post action)
In another controller's index action i use render them as:
Html.RenderAction("RegistrationForm", "Acount");
Html.RenderAction("LoginForm ", "Acount");
Everything works ok and I can register a new user, login and validate with unobtrusive validation.
The problem is when do some back-end validation in Register/Login action and if there is an error I don't know how to transfer the error to be rendered.
I've tried with PRG pattern and it works ok. I get the error displayed on the form with the preserved data, but PRG is not the way to do it.
What is an alternative solution to this problem without using ajax to validate or move those methods in the controller where the RegistrationForm/LoginForms are used?
I want to skip using TempData due to session usage in the background.
EDIT CODE SAMPLE:
class AccountController : SomeBaseController{
[HttpGet]
public PartialViewResult RegistrationForm()
{
return PartialView(new RegisterUser());
}
[HttpPost]
public ActionResult RegisterUser(RegisterUser user)
{
if (ModelState.IsValid)
{
var _user;// create domain user from Register user Model;
var _validationOutput = _userService.DoSomeAwsomeServerSideValidation(_user);// do some custom validation
if (_validationOutput.IsFault)
{
// we preseve tempdata in base controller OnActionExecuted
_validationOutput.ErrorMessages.ForEach(x => ModelState.AddModelError(_validationOutput.ErrorCode, _validationOutput));
// redirect to home controller custom error occured
return RedirectToAction("Index", "Home", user);
}
return RedirectToAction("RegistrationInfo");
}
return RedirectToAction("SomeUserInfoAction");
}
}
class HomeController : SomeBaseController {
Index(){
return View();
}}
HomeControllerMarkup {
#{Html.RenderAction("RegistrationForm", "Acount");}
#{Html.RenderAction("LoginForm", "Acount");}
}
You can manually add errors to your ModelState within your post controller using:
ModelState.AddModelError("", #"You didn't perform task XYZ");
You should then be able to return the view and display the errors in a validation summary:
#Html.ValidationSummary(false, "Login was unsuccessful because...")

cshtml file could not be found although it is under Shared folder

I have a cshtml under Shared folder. I am doing a RedirectToAction() to this page but its not looking for this file in Shared folder. Its only looking in the appropriate folder under views. It uses to look into Shared folder before and I have no idea what I could have changed that breaking lookup. Any ideas?
You cannot do a RedirectToAction to a view. You are doing (as it name suggests) a redirect to an action. It is this action that returns a view. By default it will look for views in the ~/Views/ControllerName and ~/Views/Shared. So let's suppose that you have the following action which performs a redirect:
public class HomeController: Controller
{
public ActionResult Index()
{
return RedirectToAction("Index", "Products");
}
}
which would redirect to the Index action on the Products controller:
public class ProductsController: Controller
{
public ActionResult Index()
{
return View();
}
}
Now the Index.cshtml view could be in ~/Views/Products/Index.cshtml or in ~/Views/Shared/Index.cshtml.

Resources