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

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.

Related

controller not sending to view .net core

controller not sending to view . I m trying to send request from controller to view , but its not redirecting . controller always redirect to index page. when i summit the form . its always redirecting same index page ,
controller not sending to view .controller not sending to view
My controller is sending to another view. but its not working .
public IActionResult userLogin([FromBody] Users user)
{
string apiUrl = "https://localhost:44331/api/ProcessAPI";
var input = new
{
email = user.email,
password = user.password
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
// client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/userLogin", inputJson);
// List<Users> customers = (new JavaScriptSerializer()).Deserialize<List<Users>>(json);
user = JsonConvert.DeserializeObject<Users>(json);
return View();
}
and the view page is
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#model myproject.Models.Users
#{
Layout = null;
}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Inventory Management System</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
#* <link rel="stylesheet" type="text/css" href="./includes/style.css">*#
#*<script type="text/javascript" rel="stylesheet" src="~/js/main.js"></script>*#
</head>
<body>
<div class="overlay"><div class="loader"></div></div>
<!-- Navbar -->
<br /><br />
<div class="container">
<div class="alert alert-success alert-dismissible fade show" role="alert">
#*<?php echo $_GET["msg"]; ?>*#
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#*<?php
}
?>*#
<div class="card mx-auto" style="width: 20rem;">
<img class="card-img-top mx-auto" style="width:60%;" src="./images/login.png" alt="Login Icon">
<div class="card-body">
<form id="form_login" >
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
#*<input asp-for="Name" type="text" class="form-control" id="name" required />*#
<input asp-for="email" type="email" class="form-control" id="log_email" placeholder="Enter email">
<small id="e_error" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" name="log_password" asp-for="password" id="log_password" placeholder="Password">
<small id="p_error" class="form-text text-muted"></small>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-lock"> </i>Login</button>
<span>Register</span>
</form>
</div>
<div class="card-footer">Forget Password ?</div>
</div>
</div>
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="Get Current Time" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#form_login").on("submit", function () {
var data = {
email: $("#log_email").val(),
password: $("#log_password").val(),
// Phone: $("#phone").val()
}
// data: $("#form_login").serialize(),
// var data = $("#form_login").serialize();
console.log(data);
$.ajax({
type: 'POST',
url: '/Process/userLogin',
// window.location.href = '#Url.Action("Process", "Dashboard")';
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (result) {
alert('Successfully received Data ');
console.log(result);
window.location.href = "Process/Dashboard";
// window.location.href = '#Url.Content("~/User/Home")';
// window.location.href = '#Url.Action("Process", "Dashboard")';
// window.location.href = DOMAIN + "/dashboard.php";
},
error: function () {
alert('Failed to receive the Data');
console.log('Failed ');
}
})
})
});
</script>
</body>
</html>
From your code, since you want to use JQuery Ajax to submit the form data to the action method, in the form submit event, you should use the event.preventDefault() to prevent the form submit action, then you can use JQuery Ajax to submit the form.
Second, does the Index page is the Process/Dashboard page? From your code, we can see in the Ajax success function, you will use the window.location.href to change the request URL, you can change the redirect page from here.

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.

Trouble with Fetch API displaying JSON result

I'm having trouble with Fetch API and displaying the results in html from the JSON response. I dont have a ton of experience with this.
I need to have a form where a user types in their address, and onClick of submit it will query the api. The api will then fetch (as I understand it) the results and store in a response.json file. Then the accompanying code will need to display the results in HTML.
I have tried to piece together snippets from around the web and cant get it to work right. Anytime I recreate posts such as the ones here: https://dev.to/dev_amaz/using-fetch-api-to-get-and-post--1g7d
Those all work so it's not a hosting issue blocking the response. When I try to edit it for my needs it doesnt work.
Here is an example of the response from the API when querying the Superdome in New Orleans:
input
address_components
number "1500"
street "Sugar Bowl"
suffix "Dr"
formatted_street "Sugar Bowl Dr"
city "New Orleans"
state "LA"
country "US"
formatted_address "1500 Sugar Bowl Dr, New Orleans, LA"
results
0
address_components
number "1500"
street "Sugar Bowl"
suffix "Dr"
formatted_street "Sugar Bowl Dr"
city "New Orleans"
county "Orleans Parish"
state "LA"
zip "70112"
country "US"
formatted_address "1500 Sugar Bowl Dr, New Orleans, LA 70112"
location
lat 29.951137
lng -90.081016
accuracy 1
accuracy_type "rooftop"
source "Orleans Parish"
fields
state_legislative_districts
house
name "State House District 93"
district_number "93"
senate
name "State Senate District 5"
district_number "5"
Code I'm trying to work off of
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Pulse</title>
<link rel="stylesheet" href="style/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Allerta+Stencil">
<style>
.w3-allerta {
font-family: "Allerta Stencil", Sans-serif;
}
</style>
</head>
<body>
<div class="w3-container">
<h1 class="w3-center w3-allerta w3-xxlarge">Sample get district info</h1>
<p>
<input type="submit" value="GET DATA FROM LOCAL" id="getJSON" class="w3-btn w3-white w3-border w3-border-blue w3-margin">
<input type="submit" value="GET DATA FROM API" id="getAPI" class="w3-btn w3-blue w3-margin">
</p>
<hr>
<div id="result" class="w3-container"></div>
<hr>
<div class="w3-container w3-blue">
<h2>Input Form</h2>
</div>
<form id="postData" class="w3-container w3-margin">
<p>
<input type="text" name="" placeholder="Post title ..."
class="w3-input" id="title">
</p>
<p>
<textarea name="" placeholder="Body ..." id="body" cols="20"
rows="5" class="w3-input"></textarea>
</p>
<input type="submit" value="SEND POST" class="w3-btn w3-blue">
</form>
</div>
<script>
function getAPI() {
/*********************************************
* Using jsonplaceholder API *
* ********************************************/
fetch('https://api.geocod.io/v1.4/geocode?
q=1500+Sugar+Bowl+Dr%2c+New+Orleans+LA&fields=stateleg&api_key='API-KEY-
GOES-HERE')
.then((res) => { return res.json() })
.then((data) => {
let result = `<h2 class="w3-center w3-allerta w3-xxlarge"> After user submits address to sign up</h2>`;
data ((fields)) => {
const {id, name, name2, location:{lat,lng}} = fields
result +=
`<div class="w3-panel w3-leftbar w3-border w3-
round-small w3-border-blue w3-margin">
<h5> User ID: ${id} </h5>
<ul class="w3-ul">
<li> House :
${state_legislative_districts.house.name}</li>
<li> Senate :
${state_legislative_districts.senate.name} </li>
<li> location : ${lat}, ${lng} </li>
</ul>
</div>`;
document.getElementById('result').innerHTML = result;
});
}
}
function postData(event) {
event.preventDefault();
let title = document.getElementById('title').value;
let body = document.getElementById('body').value;
title || body === "" ?
alert('Please Enter all details') :
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ title, body })
}).then((res) => res.json())
.then((data) => alert('Data Sent'))
.catch((err) => console.log(err))
}
</script>
</body>
</html>
The only information that I need to store from this response are the district information:
state_legislative_districts
house
name "State House District 93"
district_number "93"
senate
name "State Senate District 5"
district_number "5"
Appreciate any help on this matter.

Rails 5 JavaScript pipeline not working

I'm trying to apply a jQuery etalage in my Rails 5 app.
I copied all the assets file to 'app/assets' folder. I removed the CSS and JavaScripts links from html header file and my 'css' working just fine but JavaScripts not working. JavaScripts only works if I add the link in the body section of my 'html.erb' file.
My 'html.erb' file is below: `
<!DOCTYPE html>
<html>
<head>
<title>Pedal House | Single :: w3layouts</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfont-->
<link href='http://fonts.googleapis.com/css?family=Roboto:500,900,100,300,700,400' rel='stylesheet' type='text/css'>
<!--webfont-->
<!-- dropdown -->
<!--js-->
</head>
<body>
<!--banner-->
<script>
$(function () {
$("#slider").responsiveSlides({
auto: false,
nav: true,
speed: 500,
namespace: "callbacks",
pager: true,
});
});
</script>
<div class="banner-bg banner-sec">
<div class="container">
<div class="header">
<div class="logo">
<img src="assets/logo.png" alt=""/>
</div>
<div class="top-nav">
<label class="mobile_menu" for="mobile_menu">
<span>Menu</span>
</label>
<input id="mobile_menu" type="checkbox">
<ul class="nav">
<li class="dropdown1"><a>BIKES</a>
<ul class="dropdown2">
<li>NEW BIKES</li>
<li>VELOCE</li>
<li>TREK</li>
<li>PHOENIX</li>
<li>GIANT</li>
<li>GHOST</li>
<li>BINACHI</li>
<li>CORE</li>
<li>MUSTANG</li>
<li>OTHERS</li>
</ul>
</li>
<li class="dropdown1">KIDS ITEM
</li>
<li class="dropdown1">PARTS
</li>
<li class="dropdown1">ACCESSORIES
</li>
<li class="dropdown1">ABOUT US
</li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!--/banner-->
<div class="product">
<div class="container">
<div class="ctnt-bar cntnt">
<div class="content-bar">
<div class="single-page">
<!--Include the Etalage files-->
<script src="assets/jquery.etalage.min.js"></script>
<script>
jQuery(document).ready(function($){
$('#etalage').etalage({
thumb_image_width: 400,
thumb_image_height: 400,
source_image_width: 800,
source_image_height: 1000,
show_hint: true,
click_callback: function(image_anchor, instance_id){
alert('Callback example:\nYou clicked on an image with the anchor: "'+image_anchor+'"\n(in Etalage instance: "'+instance_id+'")');
}
});
});
</script>
<!--//details-product-slider-->
<div class="details-left-slider">
<div class="grid images_3_of_2">
<ul id="etalage">
<li>
<a href="optionallink.html">
<img class="etalage_thumb_image" src="assets/m1.jpg" class="img-responsive" />
<img class="etalage_source_image" src="assets/m1.jpg" class="img-responsive" title="" />
</a>
</li>
</ul>
</div>
</div>
<div class="details-left-info">
<h3>SCOTT SPARK</h3>
<h4></h4>
<p><label>$</label> 300 </p>
<h5>Description ::</h5>
<p class="desc">The first mechanically-propelled, two-wheeled vehicle may have been built by Kirkpatrick MacMillan, a Scottish blacksmith, in 1839, although the claim is often disputed. He is also associated with the first recorded instance of a cycling traffic offense, when a Glasgow newspaper in 1842 reported an accident in which an anonymous "gentleman from Dumfries-shire... bestride a velocipede... of ingenious design" knocked over a little girl in Glasgow and was fined five
The word bicycle first appeared in English print in The Daily News in 1868, to describe "Bysicles and trysicles" on the "Champs Elysées and Bois de Boulogne.</p>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
<!---->
<div class="footer">
<div class="container wrap">
<div class="logo2">
<p class="copyright">2017 | Developed By Hussain & Zaman</p>
</div>
<div class="ftr-menu">
<ul>
<li>BIKES</li>
<li>KIDS ITEM</li>
<li>PARTS</li>
<li>ACCESSORIES</li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
<!---->
</body>
</html>
My 'application.js' file:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//= require jquery
//= require jquery_ujs
//= require jquery.easydropdown
//= require jquery.etalage.min
//= require jquery.min
//= require responsiveslides.min
//= require rails-ujs
//= require turbolinks
//= require_tree .
`
I'm new with rails and I spent a lot of time to fix this problem. I tried so many ways but none worked. Some expert user please help me to fix this issue. Thanks in advance.
Have you added gem 'jquery-rails', '~> 4.3', '>= 4.3.1' to your Gemfile? In Rails 5 jquery does not come by default.

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);
}