Menu
  • HOME
  • TAGS

MVC 5 - Pass object to a shared view

Tag: redirect,asp.net-mvc-5,asp.net-mvc-viewmodel,asp.net-mvc-views,onexception

I am developing a MVC 5 internet application and have a question in regards to passing an object to a shared view.

I have a view called CustomError.cshtml in the shared folder. This view has the following model type: @model CanFindLocation.ViewModels.CustomErrorViewModel

How can I pass an object of type CanFindLocation.ViewModels.CustomErrorViewModel to this view from the protected override void OnException(ExceptionContext filterContext) function in a controller?

Here is my code:

protected override void OnException(ExceptionContext filterContext)
{
    Exception e = filterContext.Exception;

    if (e is HttpRequestValidationException)
    {
        filterContext.ExceptionHandled = false;
        customErrorViewModel = customErrorService.GetDefaultCustomError(customErrorType, "Test message.");
        RedirectToAction("CustomError", customErrorViewModel);
    }
}

Instead of the view being shown, the following function is called:

protected void Application_Error(object sender, EventArgs e)

Thanks in advance.

Best How To :

I don't think you can return view as you want, so I usually put values into TempData and make a redirection to homepage or whatever landing page.

Homepage check is there is value into this Viewbag and show error if there is error.

Controller:

public class BaseController : Controller
    {
        protected void SetError(string message, params object[] args)
        {
            TempData["UIError"] = string.Format(message, args);
        }
    }

In in my shared (master) layout view:

@if (TempData["UIError"] != null)
        {
            <div class="alert alert-danger" role="alert">
                <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                <span class="sr-only">Error:</span>
                @TempData["UIError"]
            </div>
        }

Produce different serialized JSON for a given class in different scenarios

c#,json,serialization,asp.net-mvc-5,json.net

I finally went with a mix of Wrapper classes and the methodology suggested by Raphaël Althaus: use Wrappers where some amount of sophistication may be required and use Raphaël's suggestion when simplicity will do. Here's how I am using wrappers (intentionally left out null checks): public class Entity1View1 { protected...

Embedding a Silverlight App into a MVC

c#,asp.net-mvc-5,silverlight-5.0

Do you have the Silverlight project added to your MVC project? If you don't you will need to go to your project that is your MVC, right click it and go to properties. Go to silverlight applications then add the project there too. Then try it with your current code...

Why mozilla changes the characters when i use the .net mvc statement redirect?

c#,asp.net-mvc-4,redirect,mozilla

%E2%80%8B is a URL-encoded, UTF-8 encoded ZERO-WIDTH SPACE character. You likely have one hiding in your application setting file for the ProActiveOffice-URL value. It was maybe pasted in that way, if you copied the URL from somewhere.

Get Parameter from URL using PHP

php,url,redirect

You mean like this <?php session_start(); if(isset($_SESSION['postback'])) { if($_GET['postback'] == "") { header ("Location: qualify-step2.php?postback=".$_SESSION['postback']."&city=".$_SESSION['city']); } } ?>...

Redirecting http to https

apache,.htaccess,redirect,ssl,https

You can use this in your .htaccess file. Just replace example.com with your domain and all bases should be covered. IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} !^on RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] </IfModule> ...

MVC route attribute no controller

asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing

Ok so ranquild's comment pushed me in the right direction. In my route config, I had the default route of routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); So that my homepage would still work on the url with...

Linq Conditional DefaultIfEmpty query filter

c#,linq,asp.net-mvc-5,linq-query-syntax

I solved it by adding the filter after the initial query, checking if the e.PractitionerProfiles were null. var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user =...

Redirect to edit page automatically if record exists

ruby-on-rails,ruby-on-rails-4,redirect

A redirect is a fresh request to Rails. You need to set @sale again in the edit action as it is not persisted from update. Alternatively, you can render the edit view directly from update if the update fails. That will preserve the instance variables from update....

Force WWW when URL contains path using .htaccess

.htaccess,session,url,redirect

It seems to look ok but one thing you should do is always put your other rules before the wordpress rules as a habit. When using wordpress it should generally be the last set of rules since it does all the routing. Now for the redirect, you should probably use...

Future plans to consider for asp.net mvc 5.2 web application, with releasing asp.net mvc6 (vnext)

asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-6,asp.net-mvc-5.2

I would simply recommend following the standard best practice of n-tier architecture and keeping logic related to things like querying a database in class libraries. MVC 6 is drastically different from previous versions, so there's no easy migration. You'll basically need to start a brand new project and move...

Apache htaccess redirect file

php,regex,apache,.htaccess,redirect

Try this simplified rule: RewriteEngine On RewriteRule ^aaa/(bbb/ccc/.*)$ http://newwebsite.com/$1 [R=301,L,NC] Make sure to clear your browser cache before testing....

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array: var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Brock"), new Claim(ClaimTypes.Email, "[email protected]"), new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid }; To map the information to Claim for more corrective: ClaimTypes.Name => map to username ClaimTypes.NameIdentifier => map...

htaccess redirect to subdomain based on query string

php,apache,.htaccess,redirect,joomla

You just needed to combine your rules. RewriteCond %{QUERY_STRING} (^|&)option=com_virtuemart(&|$) [NC] RewriteRule (.*) http://parts.domain.com/? [L,NC,R=301] In the second example, you had not provided the regular expression to match....

How to upgrade mvc2 to mvc5?

asp.net-mvc,asp.net-mvc-2,asp.net-mvc-5

I would highly recommend you to create a new empty MVC 5 project, and move all your files there from old MVC 2 project. If you just try to update DLLs its very hard be sure if you updated all DLLs, proj file, nugets, or at least little bit more...

Redirect stdout using exec in subscript

linux,bash,redirect,command-line,sh

Solution based on the comment from "Zaboj Campula": if /bin/grep -q "^[[:space:]]/usr/bin/enigma2_pre_start.sh$" /var/bin/enigma2.sh then echo Unpatched > /tmp/enigma.sh /bin/sed -e 's/^\t\(\/usr\/bin\/enigma2_pre_start.sh\)$/\t\. \1/g' /var/bin/enigma2.sh -i pid=`/bin/ps -o ppid= $$` && /bin/kill $pid fi ...

string.Format is not giving correct output when INR currency symbol (Rs.) come to display

c#,asp.net-mvc-5,devexpress

Your Model.CurrencySymbol string can have some symbols that can be interpreted as format specifier symbols. You can use literal string delimiter ('string', "string") so your currency symbol string will be copied to the result. For example: column.PropertiesEdit.DisplayFormatString = string.Format("'{0}' #,0.00", Model.CurrencySymbol); //Here comes string delimiters: ↑ ↑ Also you can...

How to get routevalues from URL with htmlhelpers or JavaScript?

javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-routing

To write server side code to be processed by razor engine, you have to prepend your statement with @. That will only work if that Javascript is embedded on the view. You can also do it with Javascript. Something like this should do the trick var urlParts = location.href.split('/'); var...

Inherited Property of Model is always returning Null Value

c#,asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-5

You radio button group is not inside the <form> tags so its value is not sent when the form is submitted. You need to move the radio buttons to inside the form (in the partial) and remove the hidden input for property ReportName. If this is not possible you could...

.htaccess | Too many redirects

apache,.htaccess,mod-rewrite,redirect

I'm assuming that you are trying to do two things here: Force HTTPS and www. Redirect to test.php if a certain IP is making the request The issue you were facing was due to the fact that even though the IP address was being matched, it was still being checked...

Why redirect PHP get only white page?

php,redirect

In order to debug this, there are a couple of things to do: ini_set('error_reporting', E_ALL); ini_set('display_errors', 1); switch ($_SESSION['ruolo']) { case 0: header('Location: ./php/admin/homeAdmin.php'); exit(); break; case 1: header('Location: ./php/150ore/home150.php'); exit(); break; case 2: header('Location: ./php/150ore/home150.php'); exit(); break; default: var_dump("I'm the default case!"); //If you get this, then your session...

Javascript: OS-depending Redirects doesn't work for IOS

javascript,ios,redirect,apple

Solution: don't use the "?mt=8" parameter in the iOS-Appstore-Link and the redirect will work (and open the Appstore-App on your device)

Laravel 5 pagination with trailing slash redirect to 301

php,laravel,redirect,pagination,laravel-5

If you look in your app/public/.htaccess file you will see this line: # Redirect Trailing Slashes... RewriteRule ^(.*)/$ /$1 [L,R=301] By removing it you will disable trailing slash redirect....

MvcSiteMapProvider - Enhanced bootstrap dropdown menu

c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap

node.Descendants should be node.Children Learn the difference on Descendants and Children here, CSS Child vs Descendant selectors (Never mind the post beeing about CSS, this is a generic pattern)...

Getting users from another AD Domain using PrincipalContext

c#,asp.net,active-directory,asp.net-mvc-5,active-directory-group

You need to use the underlying System.DirectoryServices.DirectoryEntry for the group: var groupEntry = (DirectoryEntry)group.GetUnderlyingObject(); (Note: according to MSDN GetUnderlyingObject() will return a DirectoryEntry, even though the return type is object.) From there you can get the member distinguished names: var memberDistinguishedNames = groupEntry.Properties["member"].Cast<string>(); The users from the other domain are...

How detailed should your repository be? Testing issues [closed]

c#,unit-testing,asp.net-mvc-5

Welcome to chasing the windmill of 100% test coverage :) You're right, there isn't a ton of value in unit testing a controller method which doesn't actually contain any logic. (Somewhere in the world, Uncle Bob just spilled his coffee.) There is some, though... By explicitly defining the expectations (in...

Excluding certain pages from being redirected to https

wordpress,.htaccess,redirect,https,http-redirect

Try using THE_REQUEST instead of REQUEST_URI: <IfModule mod_rewrite.c> RewriteEngine On # Go to https if not on careers RewriteCond %{SERVER_PORT} =80 RewriteCond %{THE_REQUEST} !/careers/[\s?] [NC] RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [R,L] # Go to http if you are on careers RewriteCond %{SERVER_PORT} !=80 RewriteCond %{THE_REQUEST} /careers/[\s?] [NC] RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [R,L] </IfModule>...

PHP redirect page works only in localhost

php,mysql,forms,redirect

<?php require_once('Connections/db.php'); ?> <?php if (isset($_POST['submit'])) { Change your above code to <?php require_once('Connections/db.php'); if (isset($_POST['submit'])) { and also remove the last ?> if you do not have html after that. After that, it should work. To turn on Error Reporting, place ini_set('display_errors',1); error_reporting(E_ALL); at the beginning of your php...

MVC: after export to excel, index action result is not getting called

asp.net-mvc-5,export-to-excel

You can't do that I'm afraid, once you have sent the header for the download, you can't then send another set of headers to do the redirect. There is a technique mentioned in this blog post which you can alter to do a redirect when a cookie appears from the...

How to redirect domain with www or without www

php,.htaccess,mod-rewrite,redirect

Just use this. Replace example.com with your domain. RewriteEngine on RewriteCond %{HTTP_HOST} ^example\.com [NC,OR] RewriteCond %{HTTPS} !^on RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L] ...

C# mvc4 - direct URL to controller

c#,asp.net-mvc-4,url,redirect

You might have forgotten to specify name of the controller in Html.ActionLink() parameter. Try Html.ActionLink("actionname","controllername");

Redirect only non-existing sub-directories to another domain using wildcard

apache,.htaccess,mod-rewrite,redirect

This should work in your .htaccess file on example.com. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/?$ http://example2.com/$1 [R=302,L] Change to R=301 when you confirm it's working. ...

How to use ajax to post json string to controller method?

jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5

Your action method is expecting a string. Create a javascript object, give it the property "data" and stringify your data object to send along. Updated code: $.ajax({ type: 'post', dataType: 'json', url: 'approot\Test', data: { "json": JSON.stringify(data) }, success: function (json) { if (json) { alert('ok'); } else { alert('failed');...

Convert SQL to linq statement

c#,linq,asp.net-mvc-5

Just use Any(), which will return a boolean, true if your query returns anything, else false. var result =(from a in _applicationRepository.GetList(a => a.ID == applicationId) from r in _roleRepository.GetList(r => r.ApplicationId == a.ID && r.Name == rolename) from au in _authorizationRepository.GetList(au => au.ApplicationId == a.ID && r.ID == au.RoleId)...

Timeout handle email php

php,email,redirect,location,sleep

Solution for the problem: Cron Job , Good learning.

Htaccess regex: exclude REQUEST_URI

regex,apache,.htaccess,mod-rewrite,redirect

Try this rule instead: RewriteCond %{HTTP_HOST} ^sub\.example\.com$ [NC] RewriteCond %{THE_REQUEST} !\s/+(aaa|bbb|ccc)/ [NC] RewriteRule . http://www.example.com%{REQUEST_URI} [R=301,L,NE] Test it after clearing your browser cache. Using THE_REQUEST instead of REQUEST_URI to make sure we use unchanged URI values as received by Apache....

Mod Rewrite Maintenance page that uses multiple URLs

windows,.htaccess,redirect,isapi-rewrite

You need to check HTTP_HOST in your condition to check for the domain and then redirect based on that. RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?foo\.bar [NC] RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000 RewriteCond %{REQUEST_URI} !/maintWWW.html$ [NC] RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC] RewriteRule .* /maintWWW.html [R=302,L] RewriteCond %{HTTP_HOST} ^(www\.)?bar\.foo [NC] RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000 RewriteCond %{REQUEST_URI} !/maintWWW2.html$...

How do I properly send __RequestVerificationToken with an ajax request in MVC5

ajax,asp.net-mvc,asp.net-mvc-5

x = $.post(window.location, {data: $('#editDrinkForm').serialize()}) is wrong. Do this: x = $.post(window.location, data: $('#editDrinkForm').serialize()) (some credit to stephen's comment)...

Knockout js unable to bind data using observableArray

knockout.js,asp.net-mvc-5

self.Employees.push(data); should be self.Employees(data);

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5

There's a handy documented guide by Rick Anderson which he wrote to upgrade from MVC4, the same applies to you with the exception of the fact that the "Old version" of DLLs he mentions will be different to the ones that you will have, but the outcome will still be...

Redirect 301 with wordpress articles from a domain to another

wordpress,.htaccess,redirect

You can use mod_rewrite for this: RewriteEngine On RewriteRule ^(\d+)/(\d+)/(\d+)/([\w\-]+)/?$ http://www.newdomain.com/$1/$2/$3/$4/ [R=302,NC,L] If you are happy with the redirect, and would like to make it permanent, you can change 302 to 301....

Web API AuthorizeAttribute does not return custom response

c#,asp.net-web-api,asp.net-mvc-5

You should override the OnAuthorization method, that use the IsAuthorized and flushs the response, or force a flush at your method. Makes more sense fill the response where the filter manipulates It.

MVC/Razor: Error at Viewbag.Title

c#,asp.net-mvc,razor,asp.net-mvc-5

Ok, the culprit was this: <ul class="list-inline text-center propertyRegionUL"> <li data-marketid="Miami-Dade" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Miami-Dade" ? "active" : "")">Miami Dade</li> <li data-marketid="Fort-Lauderdale" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Fort-Lauderdale" ? "active" : "")">Fort Lauderdale</li> <li data-marketid="West-Palm-Beach" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() ==...

Redirect specific Url variables

php,.htaccess,mod-rewrite,redirect

Try this : RewriteEngine On RewriteCond %{QUERY_STRING} ^s=([^&]+)&type=([^&]+) [NC] RewriteRule ^data.php$ /d.php?s=%1&t=%2 [NC,R,L] This will externally redirect a request for : /data.php?s=foo&type=bar to /d.php?s=foo&t=bar ...

Convert string value to english word

c#,asp.net-mvc-5

First you need to get the decimal part of the number into a separate integer, then just call your number to words function twice something like this: double value = 125.23; int dollars = (int)value; int cents = (int)((value - (int)value) * 100); Console.WriteLine("{0} dollars and {1} cents", wordify(dollars), wordify(cents));...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing

I'm not sure this is the best way of doing this, but I'll provide you with my solution to this problem. The main idea is to generate the link with all required parameters and format the href with javascript, like string.Format in c#. Generate the link: @Html.ActionLink("Link", "action", "controller", new...

mod_rewrite - force redirecting to rewritten URL

apache,.htaccess,mod-rewrite,redirect

You need a new rule for that redirect: Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / RewriteCond %{THE_REQUEST} /(?:index\.php)?\?search=([^\s&]+) [NC] RewriteRule ^ search/%1? [R=302,L,NE] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^search/(.*)$ /?search=$1 [L,QSA] ...

How to append Urls in angular routing?

asp.net,angularjs,asp.net-mvc-5,angularjs-ng-repeat,angular-ui-router

You need to change your $routeProvider.when url option, that will accept two parameter one would be albumType & other would be alubmName. You that you could get those values in your b1Ctrl using $routeParams service. Markup <li ng-repeat="album in albums"> <a ng-href="/albums/{{alubm.type}}/{{album.name}}">{{album.name}}</a> </li> Code when('/albums/:albumType/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl'...

.htaccess allow image to display directly

php,regex,apache,.htaccess,redirect

Add conditions before your rule to skip image/css/js filesdirectories: RewriteEngine On RewriteRule !\.(?:jpe?g|gif|bmp|png|tiff|css|js)$ index.php [L,NC] ...

python requests with redirection

python,authentication,redirect,curl,python-requests

There is a much simpler way to perform login to this website. import requests headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36", } s = requests.session() s.headers.update(headers) # There is a dedicated login page, which is the url of the Login button on...

LINQ: Searching inside child entities

c#,linq,asp.net-mvc-5

One option would be to use LINQ .Any(): var stringResults = db.Properties.Where(x => x.Address.Contains(id) || /* Other conditions || */ x.BayOptions.Any(g => g.Description.Contains(id))); Here, x.BayOptions.Any(g => g.Description.Contains(id)) will return true if any of the BayOptions values have a description which contains the ID....