Keep menu selection throw views - c#

I'm using mvc to go to an index that returns a partial view then render it in the body of a layout, then the different parts of the view (edit, add, delete)I use ajax and angular to render different parts of it. So I've got one index with different parts (edit, delete, add) that render the corresponding components and update them throw ajax. The thing is that I only want to render the section in the layout corresponding to the partial view, I mean in the renderbody() where the partial is rendered. But I dont want the header of the layout to to postback in order to mantain the options selected.
Here is an image:
This is the layout, the usual mvc layout:
<!DOCTYPE html>
<html lang="es">
<head>
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
#Html.ActionLink("su logotipo aquí", "Index", "Home")</p>
</div>
</div>
<select>
<option>Option 1</option>
<option>Option 2</option>
</select>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - Mi aplicación ASP.NET MVC</p>
</div>
</div>
</footer>
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
My View:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>holaaaaaaaaaaaaaaaaaa</h2>
My controller:
public ActionResult Index()
{
return PartialView();
}
In short:
I need to know how to use partial views, to render it in the layout, mantaining the options selected and not doing post back to better look of the page.

If you don't find a good solution to your problem, consider implementing bootstrap tabs http://getbootstrap.com/javascript/#tabs
I've had a similar problem and without finding a solution I've switched from select box to tabs.
Basically you play with tabs and ng-includes like this:
<ul class="nav nav-tabs">
<li class="active"><a href="" data-toggle="tab">TabName1
<ng-include src="'myFirstPartialTemplate.html'">
</a></li>
<li><a href="" data-toggle="tab">TabName2
<ng-include src="'mySecondPartialTemplate.html'">
</a></li>
</ul>

If your view is a partial view, then it should not have the property 'Layout' set.
I would do the following:
Make your index page return a View:
public ActionResult Index()
{
return View();
}
Create a another action to return your partial:
public ActionResult MyPartial()
{
return PartialView();
}
In your index page, if you wish, render your partial in the body.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>holaaaaaaaaaaaaaaaaaa</h2>
#Html.Partial("MyPartial")
Not sure if this is what you need, but I hope it helps.

Related

Ajax MVC partialView

I've run into a problem with rendering a partialView in my web application.
What I'm trying to do is using a #Ajax.ActionLink() to fill a div when a button/link is pressed with the content of another view. The issue I'm meeting is that instead of filling the div it reloads the content into a new page, rather than filling the div. All the other answers I've looked up says the same and my syntax is pretty much the same. Is there something in between I've missed or that I should've know before I started attempting this?
Here's my actionlink
<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">
<span class="icon-bar">Hei</span>
<span class="icon-bar">På</span>
<span class="icon-bar">Deg</span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
</ul>
</div>
<div>
#Ajax.ActionLink("Last inn partial view", "_LoadView", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "get", UpdateTargetId="result"})
</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/ajax");
Here's the div I want to fill in
<div class="content">
<div class="content background">
<div id="result">Her står det masse text</div>
</div>
</div>
</div>
Here's the controller
[HttpGet]
public PartialViewResult _LoadView()
{
return PartialView();
}
EDIT:
Forgot to mention that I've got a BundleConfig.cs set up and I've made sure it works as I'm rendering my css through it, though this is the first script I've tried.
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include("~/scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/scripts/bootstrap.js"));
bundles.Add(new ScriptBundle("~/bundles/ajax").Include("~/scripts/jquery.unobtrusive-ajax.js", "~/scripts/jquery.unobtrusive-ajax.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css", "~/Content/bootstrap-theme.css", "~/Content/bankstyle.css"));
}
}
EDIT: added some text to the question to make it clearer, bolded it out to make it clear. I'm very much open to alternative solutions
EDIT: Realized what I was really looking for was the modal framework in bootstrap. Thanks for the suggestions
Please run this in console:
PM> Install-Package Microsoft.jQuery.Unobtrusive.Ajax -Version 3.2.2
For install please follow next steps: https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/
Then you must use script file which is located in Scripts folder
Install the Unobtrusive js file:
Run in nuget: Install-Package Microsoft.jQuery.Unobtrusive.Ajax
Add this to your view:
#Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")
This is not the the answer to the original question but an alternative soloution:
using html.action
<div id="contentContainer">
#Html.Action("Action", "Controller")
</div>
This will call an action and render the view that you return from the action.
Found out what I was really looking for was the modal framework in bootstrap. Fixed my issues in 5 minutes.

How do I link pure html form to controller in C#

I have searched for quite some time on how to link pure html to mvc 4 controllers and came up empty. I am unsure of what I'm doing wrong, though I know there will be many errors in my code since I'm new to this.
I have a simple web page that I'm trying to link to a controller but I'm getting an error when ever I hit submit. I'm also using Bootstrap (not really used in this example but the links are there), but I'm sure that's not the source of this error and that it's server side. The error I'm getting is
0x800a1391 - JavaScript runtime error: 'Button1_Click' is undefined
The HTML page is actually an aspx because I wanted to do easy conversions of small websites over from java.
Here is the example page (It's been edited many times with different variations of buttons to submit):
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>arrggghh</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="/css/bootstrap.css" rel="stylesheet">
<link href="/css/styles.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<div class="navbar navbar-default navbar-static-top">
<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>
<a class="navbar-brand" href="index.html">Page</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li>Home</li>
</ul>
<ul class="nav navbar-nav navbar-right"></ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div id="header">
</div>
<div class="content-form-blank2">
<div>
<table class="margin">
<tr>
<td><h4>Press button.</h4></td>
</tr>
</table>
</div>
<form id="myform" action="Home" method="post">
<input type="submit" onclick="Button1_Click" />
</form>
</div>
</div>
<div class="form-navigation-bottom">
</div>
<!-- /.container -->
<!-- script references -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
And this is my example controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using arrgg.code;
namespace arrgg.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
protected void Button1_Click()
{
new arrggOut();
}
}
}
The error isn't as important as me understanding how to link pure html to the controller. Thanks in advance... if anyone has the required time to write a book about everything I'm doing wrong.
I will soon start using helpers and reading up more about asp.net and MVC
You need to post from your form submission to the correct route e.g. /Home/DoSomething. Then, in your controller, provided the route has been established, you will be mapped through to the DoSomething method in your Home controller. Do not write it as Button1_Click(). When you click that button, it should simply submit the form with the appropriate URL as its action, unless you need to do something prior to submission e.g. client side validation. Then, the controller can handle it and do something meaningful with it, described by the method name.
View:
<form id="myform" action="/Home/DoSomething" method="post">
<input type="submit" />
</form>
Controller:
namespace arrgg.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult DoSomething()
{
// Or whatever you require here...
return View();
}
}
}
Further info: http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/creating-an-action-cs
Button1_Click is JavaScript event. Call controller action from this event. Add this text to the bottom of the html:
<script>
function Button1_Click() {
$.post('/Home/Button1_Click', {}, function(res) {
});
}
</script>
To avoid JavaScript change html. Instead of:
<form id="myform" action="Home" method="post">
<input type="submit" onclick="Button1_Click" />
</form>
Write:
<form id="myform" action="/Home/Button1_Click" method="post">
<input type="submit" />
</form>
And change controller action. It must be public and return ActionResult:
[HttpPost]
public ActionResult Button1_Click()
{
return RedirectToAction("/Home/Index");
}

New to MVC can't get layout to work as desired

I am trying to implement what I think is a pretty standard "dashboard" layout. The trick is I know ASP.NET but not so familiar with MVC so this is a learning project.
I have read many an article and they have helped me progress right to the point where I am very stuck and confused.
Part of my confusion comes from an existing advanced MVC project that I am familiar with from a user perspective. This helps in that I am able to pick through the source code and match up what I am learning to what I have seen from the user perspective.
This is not the problem just an example...
For example I read here what I believe is a very good introduction to the concepts. (http://www.codeproject.com/Articles/383145/RenderBody-RenderPage-and-RenderSection-methods-in)
In the MVC project I get to pick through however I see in the _Layout
#if (IsSectionDefined("statusbar"))
{
#RenderSection("statusbar")
}
however #section statusbar is not defined in the _Layout. If I do a global search for #section I find this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section header
{
}
#section headermenu
{
}
#section statusbar
{
}
#RenderBody()
So am I correct in guessing that statusbar is defined but it is an empty shell?
If it is an empty shell how does it get populated...cause when the project is running the statusbar does indeed have information???
So again this isn't my problem it is just an example of how the information at hand is confusing me.
This IS the problem:I'm not sure when to use PartialView, RenderSection...etc
My layout renders goofy. What is goofy? The only thing I can think of is to show you a screenshot of what happens.
What I want...
Here is the code used to generate these pages. The tags etc. for bootstrap etc. are omitted for brevity.
_Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<title>#PageTitle</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
Header Stuff
</div>
</div>
<div class="row">
<div class="col-md-4">
#RenderBody()
</div>
<div class="col-md-8">
Main Content
</div>
</div>
<div class="row">
<div class="col-md-12">
Footer Stuff
</div>
</div>
</div>
</body>
</html>
Index.cshtml
#model DashboardModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="col-md-1">
<nav id="Navbar" class="navbar navbar-left" role="navigation">
<div id="organizer">
#(Html.Kendo().PanelBar()....etc....)
</div>
</nav>
</div>
<div class="col-md-3">
This is a place holder for my subnav...????
</div>
Stuff1Link cshtml
#model StuffModel
<div style="height:400px; border:dashed; border-width:thick;">
#{ Html.Kendo().MobileLayout().Name("mlay_PropStatus"); }
#(Html.Kendo().MobileView().....
</div>
Seems like layout is not put in Stuff1Link.cshtml
Can you put it like,
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
1.If your view just has some Html code just use "PartialView" :
#Html.Partial("_theLastPost")
2.If your view has controller for passing data it's better use "RenderAction":
#{ Html.RenderAction("_theLastPost"); }
and its controller
public PartialViewResult _theLastPost()
{
var a = (from c in db.Posts
orderby c.ID_Post descending
select c);
return PartialView(a);
}
3.I do not use render section . For more information about RenderSection go asp.net mvc layouts and sections with razor
I've got a post on my blog that discusses some of this you might want to check out.
The layout code you're referencing doesn't make much sense. The only purpose to declaring an empty section, really, is to fulfill a requirement that it exists, when you don't want to actually pass anything there. Since the layout is what defines whether it must be present or not, it makes no sense for it to exist there, empty. More than that, if you implement a section in your base layout, you'll get a runtime error because there's no place higher in the view chain where it's defined.
Long and short, to provide a place holder in your layout for a section you use:
#RenderSection("SectionName", [true|false])
The boolean param indicates whether views that utilize this layout must implement the section; false means it's optional, while true means it's required.
To implement a section in a view, you use:
#section SectionName
{
...
}
If you have a layout that inherits from another layout, that layout must implement all required sections in the layout it inherits from. If you want the the section to be available to views that utilize the sub-layout, you must redefine the section in the section implementation:
_Layout.cshtml
#RenderSection("Foo", true)
_SubLayout.cshtml
#{ Layout = "Views\Shared\_Layout.cshtml"; }
#section Foo
{
#RenderSection("Foo", true)
}
Finally, as to partial views vs. sections, it all comes down to whether you want to insert something into the layout or the view. For example, sections are most commonly used for inserting link tags to CSS files in the head or script tags before the closing body tag, where the view itself would not be able to touch directly. However, it's almost an apples and oranges comparison. Partials can be utilized in the layout, in the view, or even in a section. Whereas, sections can only be utilized in the layout.

Umbraco mvc, rendering partial view cannot be resolved to a type

I have a partial view located in ~/Views/Partials/menubar.cshtml .
In my ~/Views folder i have a master page Called Menubar.cshtml <- this masterpage calls the
#{ Html.RenderPartial("menubar") } but it says:
"Cannot resolve partial view "menubar"
How can i fix this? I've tried the direct path like
#{ Html.RenderPartial("~/Views/Partials/menubar.cshtml") } still the same issue.
It has to be said that im using Umbraco 4.11 and Visual studio 2012 with resharper.
Here is the code for my masterpage (it has another masterpage):
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = "Master.cshtml";
}
<div id="header">
<img src="/images/logo.gif" width="259" height="65" />
<div id="sitedescription">
<h1>Runway</h1>
<h1>Off to a great start</h1>
</div>
#{ Html.RenderPartial("Menubar"); }
</div>
#RenderBody()
This is the code for my view, simplified just to get it working at first, there will be added some logic, otherwise the view would not make sense to have:
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
<div id="mainmenu">
<ul id="topNavigation">
<li class="home current">Home</li>
<li><a class="navigation" href="/"><span>Newz</span></a></li>
<li><a class="navigation" href="/"><span>Programmering</span></a></li>
<li><a class="navigation" href="/"><span>Support</span></a></li>
<li><a class="navigation" href="/"><span>Repair</span></a></li>
</ul>
</div>
<div class="mainmenucorner"> </div>
Here is an image of the structure in visual studio:
Can anyone tell me what i'm missing here, have spend hours on this now.
EDIT
I've found out that id i locate it under /Views/Shared it'll find it automatically.. It just seems that umbraco posts this page as the main page then - any thougts?
Try renaming the partial to _menuBar.cshtml, and render it using this:
#Html.Partial("_menuBar")
It works for me.

Razor View IsAuthenticated not working as expected

I have created a simple MVC application that is using the .Net Membership Provider that is supplied with the new project.
I am trying to get the tabs to show correctly. I might not understand this right but here's my code:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>Suburban Customer Portal</h1>
</div>
<div id="logindisplay">
#Html.Partial("_LogOnPartial")
</div>
<div id="menucontainer">
<ul id="menu">
#if (Request.IsAuthenticated)
{
<li>#Html.ActionLink("ChangePassword", "ChangePassword", "Account")</li>
}else {
<li>#Html.ActionLink("Logon", "Logon", "Account")</li>
<li>#Html.ActionLink("Register", "Register", "Account")</li>
}
<li>#Html.ActionLink("ContactUs", "ContactUs", "Home")</li>
</ul>
</div>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
At this line:
#if (Request.IsAuthenticated)
I am trying to show the right tabs pending on if they are already authenticated. This is always coming out as true...
How should I be doing this? I apparently am not doing it the right way...
Thanks again!
I think you should use
#if(User.Identity.IsAuthenticated)
Well, your question is not very clear, but Request.IsAuthenticated in this line:
#if(Request.IsAuthenticated)
checks if the request has data about an authenticated user. If true, you link will be shown.
In your specific case the Change Password link will only be shown if the user is logged in.
It looks correct.
For the tabs to be hidden, that is, for Request.IsAuthenticated = false you must first logout so that the cookies that store login information are cleared from the user browser.

Categories