Not Loading Partial View in MVC Application - c#

In my _Layout.cshtml view I have
#using SiteNET.Utilities
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>"SomeTitle"</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<!-- Favicons -->
<link rel="apple-touch-icon-precomposed"
sizes="256x256"
href="#Url.Content("~/Content/Images/SiteRetro256.png")">
<link rel="shortcut icon"
href="#Url.Content("~/Content/Icons/SiteRetro.ico")">
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button"
class="navbar-toggle"
data-toggle="collapse"
data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
</button>
#Html.ActionLink(SiteNET.Utilities.Constants.Site,
"Index", "Home", null, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="#Url.MakeActive("Home")">
#Html.ActionLink("Home", "Index", "Home")
</li>
<li class="#Url.MakeActive("Index", "Contacts")">
#Html.ActionLink("Contacts", "Index", "Contacts")
</li>
</ul>
#Html.Action("_LoginPartial", "Account") <- THIS LINE
</div>
</div> <!--container-fluid-->
</div> <!--navbar-->
#RenderBody()
<hr />
...
</div>
</body>
</html>
My aim is be able to load a view model into my _LoginPartial view. So I have added the following to my AccountController class
[ChildActionOnly]
public ActionResult _LoginPartial()
{
ApplicationUser user = null;
ManageUserViewModel model = null;
string userID = User.Identity.GetUserId() ?? String.Empty;
if (!String.IsNullOrEmpty(userID))
{
user = UserManager.FindById(userID);
model = new ManageUserViewModel();
model.IsAdmin = user.IsAdmin;
}
return PartialView(model);
}
But this does not call this method from
#Html.Action("_LoginPartial", "Account")`
I have read this answer and have swapped the
#Html.Action("_LoginPartial", "Account")
to
#Html.Action("_LoginPartial", "Account", new { area = "" })
as the controller is not in the "Shared" folder. I have also tried
#Html.Action("_LoginPartial", "Account", new { area = "Controllers" })`
but I am just getting a browser error:
The page isn't redirecting properly
What am I doing wrong here?
Thanks for your time.
Edit. following #markpSmith's suggestion, I have attempted to use
#{ Html.RenderAction("_LoginPartial", "Account"); }
_but this give the same error. _

Use #Html.Partial("_LoginPartial")
You don't need to specify action in Controller as you can access User.Identity in View so update _LoginPartial with User.Identity instead of Model.

I can't see if you have attempted the:
#Html.RenderPartial()
ActionMethod (see MSDN)
making yours look similar to:
View:
#Html.RenderPartial("_LoginPartial","Account")
Controller:
(within AccountController)
public ActionResult _LoginPartial()
{
ApplicationUser user = null;
ManageUserViewModel model = null;
string userID = User.Identity.GetUserId() ?? String.Empty;
if (!String.IsNullOrEmpty(userID))
{
user = UserManager.FindById(userID);
model = new ManageUserViewModel();
model.IsAdmin = user.IsAdmin;
}
return PartialView(model);
}
Other than that, I would suggest removing the underscore and see if you can run it instead (since it is a partial view, I don't think it will be navigateable anyway)

Related

Button click in ASP.NET MVC

I am trying to understand how this ASP.NET MVC thing works compared to webforms, so I tried to simply call any method that will do the most basic thing, print some text into console, or change the text of a label.
Turns out it's nearly damn impossible to do, so I tried to look it up, everything I could find requires to first make the method in the controller which can be fine, but then it requires to add the corresponding cshtml file, put some tags over there and when you click that thing you will get the page from the new cshtml, but that's not what I want, an example how it's done from what I was able to find.
In HomeController:
namespace WebApplication9.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult ClickTest()
{
ViewBag.Message = "ClickTest.";
Debug.WriteLine("Damn...");
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
In Views -> Shared -> _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" title="more options">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div id="test-nav" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Click", "ClickTest", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
The last step is to add ClickTesty.cshtml in Views -> Home, but that's not at all what I want to do, and all the examples of a click that I was able to find show this approach, except they do other things, but what if I just want to change a label text or hide something on a current page not a new one? I couldn't find any info how to do it using C#, in webforms there's no problem to change some text or hide something on the current page, even using javascript, but here I can't find a way.
To see a Debug.WriteLine in Visual Studio here's what you can do:
Add this code:
<input type="button" value="Click here to debug log" onclick="location.href='#Url.Action("ClickTest", "Home")'" />
Inside the "main" tag on your application
HomeController should look something like this:
public IActionResult ClickTest()
{
Debug.WriteLine("Damn...");
return View("Index");
}
Run the application in Debug mode (F5 by default)
Go to the Home page, click the button 'Click here to debug log'
You will see at the Output pane your Debug.WriteLine
What you are doing right now on your code is to redirect to a different view that doesn't exists. So, returning the View("Index") is doing the trick to not have an error and see your log.

How to make navbar dropdown with picture select

I am trying in ASP.NET MVC in navbar put dropdown menu with select language. When I click on first dropdown button all navbar button need to change language. I wrote Language Controller and it works but my problem is that I want to have in navbar only show pictures of country and I try everything and always I see and letters and pictures.
I want to have only pictures of flag, without ENG.
One example of code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Brig</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<div class="main_manu">
<div class="title">
<h2>Brig</h2>
<br />
<div class="navbar navbar-inverse navbar-fixed" id="navbarMenu">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="navbar-colapse">
<ul class="nav navbar-nav">
<li class="dropdown">
#Html.LabelFor(model => model.ChoseLanguage) <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li><a>#Html.ActionLink("ENG", "Change", "Language", new { LanguageAbbrevation = "en" }, null)</a><img class="demo cursor" src="~/pictures/flag/gb.jpg" style="width:25%"></li>
<li><a>#Html.ActionLink("SPA", "Change", "Language", new { LanguageAbbrevation = "spa" }, null)</a><img class="demo cursor" src="~/pictures/flag/spa.png" style="width:25%"></li>
</ul>
</li>
<li>#Html.ActionLink(Resources.Resource.Home, "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })</li>
<li>#Html.ActionLink(Resources.Resource.Services, "Info", "Services", new { area = "" }, new { #class = "navbar-brand" })</li>
<li>#Html.ActionLink(Resources.Resource.Gallery, "Gallery", "Gallery", new { area = "" }, new { #class = "navbar-brand" })</li>
<li>#Html.ActionLink(Resources.Resource.Apartment, "Apartment", "Apartment", new { area = "" }, new { #class = "navbar-brand" })</li>
<li>#Html.ActionLink(Resources.Resource.Contact, "SendEmail", "Contact", new { area = "" }, new { #class = "navbar-brand" })</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - Brig</p>
</footer>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>
I will appreciate your help. Thank you.

How to get browser querystring in partial view

I create my partial view with #Html.Action() like so:
#Html.Action("Index", "AreaMenu", new { Area = "" })
In the partial view's controller I'd like to get the browser querystring, unfortunately if I try to get it from System.Web.HttpContext.Current.Request.Url.AbsolutePath I get url to the controller not what's in the address bar.
How do I get this?
#inherits System.Web.Mvc.WebViewPage
#using System.Web.Mvc.Html;
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
var location = window.location;
</script>
<div class="row">
#Html.Action("Index", "AreaMenu", new { Area = "" })
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div id="ajax-content">
<!--Start Breadcrumb-->
<div class="row">
<div id="breadcrumb" class="col-xs-12">
<ol class="breadcrumb pull-left">
<li>
<a href='#Url.Action("Index", "Home", new { area = "" })'>
<i class="fa fa-home"> </i> Nuclei
</a>
</li>
<li>
<a href='#Url.Action("Index", "Home", new { area = (string)ViewBag.AreaName })'>#ViewBag.CurrentModule.Name</a>
</li>
<li>
<a href=''>#ViewBag.AreaView</a>
</li>
</ol>
</div>
</div>
<!--End Breadcrumb-->
#RenderBody()
</div>
</div>
<!--End Content-->
</div>
MVC treats this as a standalone request (as if you are entering this action in the address bar). That is why are seeing the controller in the AbsolutePath and not what is in the address bar.
You could pass the querystring as a parameter in your Action.
see: https://stackoverflow.com/a/14152825/893543
OR
Couldn't the model you use to generate the page contain everything you need? The query string is what was passed to the controller that made the page, just add the properties you need to the model?

Unable to open the cshtml page

I have developed an application and deployed to cloud. By default index page is loading but once index page is loaded on click on it it will open other page(cshtml page). But i am getting blank page . Please help
Index.cshtml code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Create Invoice Online for Free & Download PDF</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../Content/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../Content/bootstrap-responsive.min.css" />
<link rel="stylesheet" type="text/css" href="../Content/quick-invoice.css" />
<script type="text/javascript" src="../Content/jquery.js"></script>
<script type="text/javascript" src="../Content/bootstrap.min.js"></script>
<meta name="google-site-verification" content="FB0t_l2pYlfmLe1hzPyjLXXhDF8Bufut_nDhCP5brrQ" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="/">Invoices generator</a>
<div class="nav-collapse">
<ul class="nav">
<li class="active"><i class="icon-home icon-white"></i>Home</li>
<li><i class="icon-file icon-white"></i> Invoice Templates</li>
</ul>
</div>
</div>
</div>
</div>
<div class="container layout">
<div class="row">
<div class="span9">
<div class="container-narrow">
<div class="container-narrow jumbotron">
<h1>Shopping Cart Online Invoice Generator</h1>
<p class="lead">Create & Send your invoice without having to register, and download as <strong>PDF, </strong>quickly & easily for free, email your invoice Select an invoice template from our invoices templates list, Save or send your invoice in minutes</p>
<hr /> Create your invoice
<hr />
</div>
</div>
<div class="pop-layouts">
<h4>Invoice Templates</h4>
<ul class="thumbnails">
<li>
<h4>Shopping Cart Invoice Template</h4>
<a class="thumbnail" href="create" title="Shopping Cart Invoice Template">
<img src="../Images/057e7_b4a13_1.jpg" alt="" date-large="../Images/4dad1_733d6_1.png" />
</a>
<div class="caption">
<!--<i class="icon-eye-open icon-white"></i> Preview-->
<i class="icon-plus-sign icon-white"></i> Create
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('shopping-cart-invoices', 'UA-47492117-1', 'mybluemix.net');
ga('send', 'pageview');
</script>
</body>
</html>
Startup.cs
using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.AspNet.StaticFiles;
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseServices(services =>
{
services.AddMvc();
});
app.UseFileServer(new FileServerOptions()
{
EnableDirectoryBrowsing = false,
});
app.Use(async (context, next) =>
{
Console.WriteLine(context.Request.Path);
try
{
await next();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Default",
template: "{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "CreateInvoice",
template: "{controller=CreateInvoice}/{action=Create}/{id?}"
);
routes.MapRoute(
name: "Preview",
template: "{controller=Preview}/{action=preview}/{id?}"
);
routes.MapRoute(
name: "Thanks",
template: "{controller=Thanks}/{action=Thankyou}/{id?}");
});
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
You should be using
#Html.actionlink("Create", "CreateInvoice")
This will allow you to declare the action and the controller
It also means that you will get build errors if the action or controller do not exist

Problems with Partial Views in ASP.NET MVC 2

this is the master page :
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="header1" runat="server" />
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
</div>
<div id="logindisplay">
<% Html.RenderPartial("LogOnUserControl"); %>
</div>
<div id="menucontainer">
<ul id="menu">
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About", "About", "Home")%></li>
<li><%= Html.ActionLink("Imoveis", "Index", "Categoria")%></li>
<li><%= Html.ActionLink("Admin", "Index", "Admin")%></li>
<li><%= Html.ActionLink("User", "Index", "User")%></li>
</ul>
</div>
</div>
<div id="left">
<% Html.RenderPartial("~/Views/Imovel/Pesquisa.ascx"); %>
</div>
<div id="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
<div id="footer">
</div>
</div>
</div>
</body>
</html>
Partial View
<%= Html.DropDownList("categoria_id", (SelectList)ViewData["Categoriass"], "--Selecciona um--")%>
<div class="editor-label">
<%= Html.LabelFor(model => model.categoria_id) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.categoria_id, (SelectList)ViewData["Categorias"], "--Selecciona um--")%>
<%= Html.ValidationMessageFor(model => model.categoria_id) %>
</div>
This is the problem:
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
**ViewData["Categoriass"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);**
return View();
}
Since the partial view is in the master page, how do I get its model?
I think you should create an ActionFilter and apply it on your controllers.
Create an action filter like this
public class DataForMasterPageAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//initiate your repository
var catRepository = ...;
//then create the viewdata like so
filterContext.Controller.ViewData["Categorias"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);
}
}
Then apply it on the controller and it will be available for all actions as well. Like so;
[DataForMasterPage]
public class CategoriaController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
On the partial view you just call the ViewData as usual, no need to change anything
<div class="editor-label">
<%= Html.LabelFor(model => model.categoria_id) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.categoria_id, (SelectList)ViewData["Categorias"], "--Selecciona um--")%>
<%= Html.ValidationMessageFor(model => model.categoria_id) %>
</div>
Might have performance issues, but its one of the simplest ways to avoid setting the ViewData on every method.
You can create base class for your controllers and set it during creation if you need to query for it with every request:
public class BaseController : Controller
{
public BaseController()
{
var catRepository = ...;
ViewData["Categoriass"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);
}
}
That is not really efficient,because it will be executed with every controller. You can also create action filter which sets ViewData and apply it where needed.
I have try Nick Masao & LukLed solutions, both of them are works.
However, the viewdata is set for masterpage, in my case, i assume masterpage will render every page.
I have to
apply the [DataForMasterPage] attribute (Nick Masao's solutions) or
or
inherits the BaseController (LukLed's solutions)
on every View's Controller.
So, is it possible create a Class and invoke on Global.asax Application_Start event to make it Set viewdata everytimes?
You could also create a ContentPlaceHolder where you want the partial view to render and call the RenderPartial() from the underlying pages. That way you can pass the model as usual.

Categories

Resources