How to Suppress Navigation on Home Page of my MVC4 Application? - asp.net-mvc-4

I'm using the standard MVC4 template in VS 2012. It came with a _layout.cshtml file which is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - iLoveSport</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/kendo")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/kendo")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<img src="~/Images/logo.png" alt="ILoveSport Logo" />
</div>
<div class="float-right">
<section id="login">
</section>
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("AFL", "Index", "AFL")</li>
<li>#Html.ActionLink("NRL", "Index", "NRL")</li>
<li>#Html.ActionLink("State of Origin", "Index", "State of Origin")</li>
<li>#Html.ActionLink("Cricket", "Index", "Cricket")</li>
<li>#Html.ActionLink("Golf", "Index", "Gof")</li>
<li>#Html.ActionLink("Motorsport", "index", "Motorsport")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</nav>
</div>
</div>
</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">
</div>
</div>
</footer>
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
</html>
The _viewstart.cshtml contains the following:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
What must be modified so that the navigation in my _layout.cshtml page is suppressed on the home page only? The home page needs to have a button that will then trigger the inner page which is currently my home page. Do I create a new layout file suppressing the menu and change viewstart to load it instead? Or, can this be done via another means?
Thanks for your help and guidance.
Update:
My Home Controller now is as follows:
[ChildActionOnly]
public ActionResult NavigationMenu()
{
string controller = ControllerContext.
ParentActionViewContext.RouteData.Values["controller"].ToString();
string action = ControllerContext.
ParentActionViewContext.RouteData.Values["action"].ToString();
if (controller == "Home" && action == "Index")
return Content("");
else
return PartialView("_Menu");
}
My _layout.cshtml is as follows:
<nav>
#Html.Action("NavigationMenu","Partial")
</nav>
However, I receive a debug error stating:
System.Web.HttpException: The controller for path '/' was not found or does not implement IController.
This error is thrown on the layout.cshtml file. How should this be remedied?

You can define your navigation menu as partial view. And render this partial view in your layout.
Inside action method of this partial view, you can check for the controller and action. If it is your home page you can return empty content. Otherwise, return your navigation menu.
Partial View
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("AFL", "Index", "AFL")</li>
<li>#Html.ActionLink("NRL", "Index", "NRL")</li>
<li>#Html.ActionLink("State of Origin", "Index", "State of Origin")</li>
<li>#Html.ActionLink("Cricket", "Index", "Cricket")</li>
<li>#Html.ActionLink("Golf", "Index", "Gof")</li>
<li>#Html.ActionLink("Motorsport", "index", "Motorsport")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</nav>
Action Method
[ChildActionOnly]
public ActionResult NavigationMenu()
{
string controller = ControllerContext.
ParentActionViewContext.
RouteData.Values["controller"].ToString();
string action = ControllerContext.
ParentActionViewContext.
RouteData.Values["action"].ToString();
if(controller == "Home" && action == "Index")
return Content("");
else
return PartialView("_NavigationPartial");
}
Rendering Partial View
#Html.Action("NavigationMenu", "Partial")
I have not tested the code, but most of it should be fine.

Related

Returning html ID via path of Views of MVC controller

I am using wizard in my page and server side validation using razor view.
output page
Index.cshtml
For validation in #step-3/#step-2 wizard i want my page goes to id->step-3 but it goes to #step-1 or at the start of wizard page
I have to return the id of html page in returning views of controller.controller.cshtml
You can try to use Tempdata and js,here is a demo:
action:
[HttpPost]
public IActionResult Index(Contact contData)
{
TempData["id"] = "step-3";
return View();
}
View:
<div class="tab-content">
<div id="step-1" class="tab-pane fade">
<h3>Step 1</h3>
<p>Some content in step 1.</p>
</div>
<div id="step-2" class="tab-pane fade">
<h3>Step 2</h3>
<p>Some content in step 2.</p>
</div>
<div id="step-3" class="tab-pane fade">
<h3>Step 3</h3>
<p>Some content in step 3.</p>
</div>
</div>
<form method="post">
<button>submit</button>
</form>
#section Scripts{
<script>
$(function () {
var s = "#TempData["id"]";
var indexValue=0;
$(".tab-pane").each(function (index) {
if ($(this).attr("id") == s) {
$(this).addClass("in active");
indexValue=index;
} else {
$(this).removeClass("in active");
}
})
$(".myClass").each(function (index) {
if (indexValue==index) {
$(this).addClass("active");
indexValue=index;
} else {
$(this).removeClass("active");
}
})
})
</script>
}
result:

MVC Express - Data does not carry over in view once form is submitted

I am working on a very basic weather app to learn MVC architecture. However, I am having an issue with my page reloading once I submit the form and then data from that submission not coming over into the next newly rendered page.
Most of my logic for my page is in my controller.js file. In my view I have a form where the user fills in a city, and then my getWeather function makes an API call where it gets the city's temperature. From there my controller.js should re-render the index page, but pass in the string It is currently ${temp} °F in ${city}.
At least, that's how its supposed to work. Unfortunately when the page reloads the weather const is null and I then have my function catch the error and give me the message "that city is not available".
I have tested my API to make sure that it is correctly retrieving the data, by console.logging the res object, and I am getting that perfectly.
Also, I should note I bring in Weather function from my model. The only thing it does is test to see if the user inputted anything into the form and if they didn't it creates the error "Please enter the name of the city." I don't think it is the source of my issue or the fix for it.
I guess what I'm looking for is a way to prevent my page from reloading when I submit the form, or a way to not lose the data in my function when the page reloads. Any help would be greatly appreciated!
const axios = require('axios')
const API_KEY= "8d130a4fe5369b01d1fe629bccbe0926";
const Weather = require("../model/Weather")
exports.renderHomePAge = (req, res) => {
res.render("index")
}
exports.getWeather = (req, res, ) => {
const city = req.body.city
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=imperial`
const weather = new Weather(city)
weather.validateUserInput()
if(weather.errors.length){
res.render("index", {error: weather.errors.toString()})
} else {
axios.get(url)
.then((response)=>{
// console.log(response)
const {temp} = response.data.main
const {city} = response.data.city
res.render("index", {
weather: `It is currently ${temp} °F in ${city}.`
})
})
.catch((err) =>{
console.log(err)
res.render("index", {
weather: `That city is not avaible`
})
})
}
}
exports.renderAboutPAge = (req, res) => {
res.render("About")
}
I don't think its neccessary for this issue, but just incase here is my index.hbs file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Weather | Home</title>
<!-- Bootstrap core CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/about">About</a>
</li>
</ul>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-12 text-center main">
<div>
<h1 class="mt-5">MVC Weather Finder</h1>
<p class="lead">Enter the name of the city and press search!</p>
</div>
<div>
<form action="/" method="post">
<input name="city" type="text">
<button>Go!</button>
</form>
<div class="mt-3">
{{weather}}
{{error}}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
It turns out I was pulling data from my response object incorrectly and that was causing the issue.

How to pass IEnumerable model to _Layout.cshtml

I need to pass a model to _Layout page for dynamic content editing.
Here is my _Layout
#model IEnumerable<Test.Models.Article>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
...
Later in _Layout I need to use this:
#Html.Raw(Model.Where(x => x.Id == 1).Single().Content) - this works fine
<a asp-controller="Articles" asp-action="Edit" asp-route-id="1">Edit</a> - error after clicking the edit button
This concept is working fine on all pages like Index, About etc. but not on _Layout.cshtml.
I get this error:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Test.Models.Article', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[Test.Models.Article]'.
What shoud I do?
Edit:
Here is my HomeController:
public class HomeController : Controller
{
public ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await _context.Article.ToListAsync());
}
public async Task<IActionResult> About()
{
return View(await _context.Article.ToListAsync());
}
}
Here is my ArticleController:
public class ArticlesController : Controller
{
public ApplicationDbContext _context;
public ArticlesController(ApplicationDbContext context)
{
_context = context;
}
// GET: Articles
public async Task<IActionResult> Index()
{
return View(await _context.Article.ToListAsync());
}
// GET: Articles/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var article = await _context.Article.FindAsync(id);
if (article == null)
{
return NotFound();
}
return View(article);
}
// POST: Articles/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Content")] Article article)
{
if (id != article.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(article);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ArticleExists(article.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(article);
}
The whole _Layout:
#model IEnumerable<Test.Models.Article>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - PermanentTetovani</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/css/default.css" />
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.min.css" />
</environment>
</head>
<body>
<partial name="_CookieConsentPartial" />
<!-- HEADER : begin -->
<header id="header" class="m-animated">
<div class="header-bg">
<div class="header-inner">
<!-- HEADER BRANDING : begin -->
<div class="header-branding">
<a asp-controller="Home" asp-action="Index"><img src="../images/logo.png" alt="Permanentní tetování" data-hires="../images/logo.2x.png" width="291"></a>
</div>
<!-- HEADER BRANDING : end -->
<!-- HEADER NAVIGATION : begin -->
<div class="header-navigation">
<!-- HEADER MENU : begin -->
<nav class="header-menu">
<button class="header-menu-toggle" type="button"><i class="fa fa-bars"></i>MENU</button>
<ul>
<li class="#((ViewBag.PageName == "Index") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="Index">Úvodní stránka</a></span>
</li>
<li class="#((ViewBag.PageName == "About") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="About">O nás</a></span>
</li>
<li class="#((ViewBag.PageName == "Gallery") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="Gallery">Galerie</a></span>
</li>
<li class="#((ViewBag.PageName == "Contact") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="Contact">Kontakt</a></span>
</li>
</ul>
</nav>
<!-- HEADER MENU : end -->
</div>
<!-- HEADER NAVIGATION : end -->
<!-- HEADER PANEL : begin -->
<div class="header-panel">
<button class="header-panel-toggle" type="button"><i class="fa"></i></button>
<!-- HEADER RESERVATION : begin -->
<div class="header-reservation">
<a asp-controller="Home" asp-action="Contact" class="c-button">Domluvit si schůzku</a>
</div>
<!-- HEADER RESERVATION : end -->
<!-- HEADER CONTACT : begin -->
<div class="header-contact">
<ul>
<!-- PHONE : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-phone"></i>
<strong>721 805 741</strong>
</div>
</li>
<!-- PHONE : end -->
<!-- EMAIL : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-envelope-o"></i>
777michaelahavlova<br>
##seznam.cz
</div>
</li>
<!-- EMAIL : end -->
<!-- ADDRESS : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-map-marker"></i>
<strong>PERMANENT TETOVÁNÍ</strong><br>
Jihočeská univerzita, Vančurova 2904<br>
Tábor 390 01
</div>
</li>
<!-- ADDRESS : end -->
<!-- HOURS : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-clock-o"></i>
<dl>
<dt>Po. - Pá.:</dt>
<dd>Dle dohody</dd>
<dt>So.:</dt>
<dd>Dle dohody</dd>
<dt>Ne.:</dt>
<dd>Zavřeno</dd>
</dl>
</div>
</li>
<!-- HOURS : end -->
</ul>
</div>
<!-- HEADER CONTACT : end -->
</div>
<!-- HEADER PANEL : end -->
</div>
</div>
</header>
<!-- HEADER : end -->
<!-- WRAPPER : begin -->
<div id="wrapper">
#RenderBody()
<!-- BOTTOM PANEL : begin -->
<div id="bottom-panel">
<div class="bottom-panel-inner">
<div class="container">
<div class="row">
<div class="col-md-6">
<!-- BOTTOM TEXT : begin -->
<div class="bottom-text various-content">
<h3>O našem studiu</h3>
<!--
<p><strong>Permanentní make-up</strong> provádím v Táboře v Jihočeské univerzitě, kde nabízím tyto služby: <strong>permanentní tetování obočí, rtů a očních linek</strong>.</p>
<p>Je potřeba se nejprve předem objednat!</p>
-->
#Html.Raw(Model.Where(x => x.Id == 1).Single().Content)
<a asp-controller="Articles" asp-action="Edit" asp-route-id="1">Edit</a>
</div>
<!-- BOTTOM TEXT : end -->
</div>
<div class="col-md-6">
<!-- BOTTOM SUBSCRIBE : begin -->
<div class="bottom-subscribe various-content">
<h3>Kontakt</h3>
<p>Využijte prosím náš kontaktní formulář.</p>
<a asp-controller="Home" asp-action="Contact" class="c-button">Kontaktujte nás</a>
</div>
<!-- BOTTOM SUBSCRIBE : end -->
</div>
</div>
</div>
</div>
</div>
<!-- BOTTOM PANEL : end -->
<!-- FOOTER : begin -->
<footer id="footer">
<div class="container">
<!-- FOOTER BOTTOM : begin -->
<div class="footer-bottom">
<div class="row">
<div class="col-md-6 col-md-push-6">
<!-- FOOTER MENU : begin -->
<nav class="footer-menu">
<ul>
<li><a asp-controller="Home" asp-action="Index">Úvodní stránka</a></li>
<li><a asp-controller="Home" asp-action="About">O nás</a></li>
<li><a asp-controller="Home" asp-action="Gallery">Galerie</a></li>
<li><a asp-controller="Home" asp-action="Register">Administrace</a></li>
</ul>
</nav>
<!-- FOOTER MENU : end -->
</div>
<div class="col-md-6 col-md-pull-6">
<!-- FOOTER TEXT : begin -->
<div class="footer-text">
<p>
©
<script type="text/javascript">
var today = new Date()
var year = today.getFullYear()
document.write(year)
</script>
PermanentTetovani.cz | Vytvořil ProgNet.cz
</p>
</div>
<!-- FOOTER TEXT : end -->
</div>
</div>
</div>
<!-- FOOTER BOTTOM : end -->
</div>
</footer>
<!-- FOOTER : end -->
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
#RenderSection("Scripts", required: false)
</body>
</html>
#Lukáš, I found the reason of your exception and will try my best to describe it.
From the process below, when reload edit view, it will load _layout.cshtml then render Edit.cshtml.You defined the #model IEnumerable<Test.Models.Article>
but return view(Ariticle).
What's the simplest solution?
open Views/Articles/Edit.cshtml add codes below
#{
Layout = null;
}
Screenshots of test:
WARNING
I have to remind you even though Edit works but others still have same problems.
_Layout.cshtml was added to each Views from _ViewStart.cshtml.
The layout specified can use a full path (for example, /Pages/Shared/_Layout.cshtml or /Views/Shared/_Layout.cshtml) or a partial name (example: _Layout). When a partial name is provided, the Razor view engine searches for the layout file using its standard discovery process. The folder where the handler method (or controller) exists is searched first, followed by the Shared folder. This discovery process is identical to the process used to discover partial views.
The details about Layout in ASP.NET Core.

Include Local javascript file with global dependency for only a view

I have a view like this
#model IEnumerable<DuckingOctoBear.Models.PostViewModel>
<p>
#if (User.IsInRole("Administrator") || User.IsInRole("Editor"))
{
#Html.ActionLink("Create New", "Create")
}
</p>
<div class="">
#foreach (DuckingOctoBear.Models.PostViewModel item in Model)
{
<a href="/Posts/Details/#item.Post.Id" class="post-element">
<h4>#Html.DisplayFor(modelItem => item.Post.Title)</h4>
<h6>
Inserted by #item.User.UserName at #item.Post.Date.ToString("dd MMMM yyyy hh:ss")
</h6>
<article>
#Html.Raw(item.Post.Text)
</article>
<span>
#if (User.IsInRole("Administrator") || User.IsInRole("Editor"))
{
#Html.ActionLink("Edit", "Edit", new { id = item.Post.Id })
<span>|</span>
}
#Html.ActionLink("Details", "Details", new { id = item.Post.Id })
<span>|</span>
#if (User.IsInRole("Administrator"))
{
#Html.ActionLink("Delete", "Delete", new { id = item.Post.Id })
<span>|</span>
}
</span>
</a>
}
</div>
...where I would like include a Javascript file which have strong dependencies to other Javascript files already included in the _Layout.cshtml
<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")
How can I include that local file without register it in a bundle, and so for all views?
Ok epic fail
for this _Layout.cshtml
<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)
I could add just a new section
#RenderSection("LocallyScriptLibrary", required: false)
then in the target view doing just:
#section LocalScriptLibrary{
<script src="~/Scripts/LocalLibrary.js"></script>
}

Model in Layout breaks other pages

I have a design flaw based on my lack of MVC4 experience.
The issue is that I have a model in my Layout...
#model BasicFinanceUI.Models.LoginModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet"/>
<title>#ViewBag.Title</title>
</head>
The reason it's on my Layout, is that the Login button is on the layout screen, and it launches a modal popup, which has fiends that use the model.
So, at the bottom of the layout, I have:
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3>Login</h3>
<div class="modal-body">
#using (Html.BeginForm("LoginUser", "User"))
{
<p>
#Html.LabelFor(x => x.Username)
#Html.TextBoxFor(x => x.Username)
</p>
<p>
#Html.LabelFor(x => x.Password)
#Html.PasswordFor(x => x.Password)
</p>
<p>
#Html.LabelFor(x => x.RememberMe)
#Html.CheckBoxFor(x => x.RememberMe)
</p>
<div class="modal-footer">
<input type="submit" value="Login" name="btn_login" class="btn btn-default" />
<a class="btn btn-primary" data-dismiss="modal">Cancel</a>
</div>
}
</div>
</div>
</div>
</div>
I also have a Login and Logout button on my /Home/Index, so the user see's two login buttons when on the default page. One on the main page, and one in the header/menu, which is shared.
I think having the model, and probably all the Login screen code, on the Layout page, might be the problem here. How should I be implementing this?
I need the Login button on the Index.cshtml page (Default), and the button in the Layout's menu at the top. And both use the model popup code shown above.
First build the view like you have it but instead of using helpers just build the html fields. Make sure you put an id or a class on the fields that we can use as a selector
<input type="text" class="txtUserName" /> etc
then make sure you have jquery referenced on the page and put this on the bottom of your screen
<script type="text/javascript">
$(document).ready(function(){
$('.btnSubmit').on('click', function(){
$.ajax({
url: "#(Url.Action("Action", "Controller")",
type: "POST",
contentType: "application/json",
data: { UserName: $('.txtUserName').val(), Password: $('.txtPassword').val() }
cache: false,
async: true,
success: function (result) {
alert('Login Successful!');
window.location = "#Url.Action("Index", "Controller")";
}
});
});
});
</script>
then on your controller you need to have a method set up to receive the ajax call
[HttpPost]
public ActionResult Login(string UserName, string Password){
//Check the user name and password against the database
//from here http://stackoverflow.com/questions/10608198/asp-net-mvc3-returning-success-jsonresult
var result=new { Success="True", Message="Success"};
return Json(result, JsonRequestBehavior.AllowGet);
}