Retrieve the current view name in ASP.NET MVC?

Viewed 51647

I have a partial view (control) that's used across several view pages, and I need to pass the name of the current view back to the controller - so if there's e.g. validation errors, I can re-draw the original view.

A workaround way to do it would be (in the controller methods)

var viewName = "Details"; // or whatever
ViewData["viewName"] = viewName;
return(View(viewName, customer));

and then in the partial itself, render it as

<input type="hidden" name="viewName" 
    value="<%=Html.Encode(ViewData["viewName"])%>" />

Question is - is there some property or syntax I can use to retrieve this directly instead of setting it from the controller? I've tried the obvious:

<input type="hidden" name="viewName" 
    value="<%=Html.Encode(this.Name)%>" />

but this doesn't work. What am I missing here?

Thanks.

10 Answers

If you just want the action name then this would do the trick:

public static string ViewName(this HtmlHelper html)
{
    return html.ViewContext.RouteData.GetRequiredString("action");
}

Shouldn't you be using a validation method like Nerd Dinner implements?

That way you don't actually need to do all this and you can just return the View.

You can use Razor:

in your View header

@{
    ViewData["Title"] = "YourViewName";    
}

in your View HTML

@{
   var _nameCurrentView = ViewContext.ViewData["Title"];
}

use in your html the variable @_nameCurrentView

  <li class="breadcrumb-item active">@_nameCurrentView</li>

or use in your action

  ViewData["Title"]
Related