Parser Error in this View - asp.net-mvc

Just melt my brain out trying to figure out why I'm getting Parser Error with this code:
#foreach(var news in Model.News)
{
if (news.Order > 0)
{
<text>
<div class="colPrincipal newsTop newsBlue">
<article>
<a href="news.html">
</text>
if (news.LayoutExibitionMainImage)
{
<text>
<span class="newsImg">
<img src="~/Content/img/news/not2.jpg" alt="" title="" />
</span>
</text>
}
<text>
<hgroup>
</text>
if (news.LayoutExibitionMainTitle)
{
<text>
<h1>
#Html.Raw(news.Title)
</h1>
</text>
}
if (news.LayoutExibitionMainSummary)
{
<text>
<h2>
#Html.Raw(news.Summary)
</h2>
</text>
}
<text>
</hgroup>
<span class="btnMais">Ler este artigo</span>
</a>
</article>
</div>
</text>
}
}
Its throwing this error on my last <text> tag:
Is there a way to fix this or a better way to print that HTML code? I hope this is not a silly question because is wierd to me.

Try this, i think you have an issue with all those text tags. Also text is not allowed in the hgroup tags.
#foreach(var news in Model.News)
{
#if (news.Order > 0)
{
<div class="colPrincipal newsTop newsBlue">
<article>
<a href="news.html">
#if (news.LayoutExibitionMainImage)
{
<span class="newsImg">
<img src="~/Content/img/news/not2.jpg" alt="" title="" />
</span>
}
<hgroup>
#if (news.LayoutExibitionMainTitle)
{
<h1>
#Html.Raw(news.Title)
</h1>
}
#if (news.LayoutExibitionMainSummary)
{
<h2>
#Html.Raw(news.Summary)
</h2>
}
</hgroup>
<span class="btnMais">Ler este artigo</span>
</a>
</article>
</div>
}
}

Related

How to disable buttons based on data model values?

I am building a mini online shopping CMS project for collage.
I finished the project and now I want to add a feature where I have limited quantity of products.
When the quantity is equal to 0 then product is shown as 'out of stock' and my 'Add to cart' button becomes disabled.
I have added a 'quantity' property to my product class and now I need to change something in the Index view of the product.
I tried few options and it does not seem to work.
Here is the code for the Index.cshtml page.
#model IEnumerable
<Product>
#{ ViewData["Title"] = "Products"; }
<h1 class="display-4 pb-5">All Products</h1>
<div class="row">
#foreach (var item in Model)
{
<div class="col-4">
<div class="ajaxbg d-none">
<img src="~/Images/ajax_loader.gif" />
<p class="lead alert alert-success text-center d-none">
The product has been added!
</p>
</div>
<img src="~/Media/Products/#item.Image" class="img-fluid" alt="" />
<h4>#item.Name</h4>
<div>
#Html.Raw(item.Description)
</div>
<p>
#item.Price.ToString("C2")
</p>
<p>
<a asp-controller="Cart" asp-action="Add" asp-route-id="#item.Id" data-id="#item.Id" id="addToCartButton" class="btn btn-primary addToCart">Add to cart</a>
</p>
#if (item.Quantity == 0) { }
</div>
}
#if (ViewBag.TotalPages > 1) {
<div class="d-flex w-100 justify-content-center">
<pagination page-count="#ViewBag.TotalPages" page-target="/products" page-number="#ViewBag.PageNumber" page-range="ViewBag.PageRange"></pagination>
</div>
}
</div>
#section Scripts {
<script>
function DisableBtn() {
document.getElementById("addToCartBUtton").disabled = true;
}
$(function() {
$("a.addToCart").click(function(e) {
e.preventDefault();
let ajaxDiv = $(this).parent().parent().find("div.ajaxbg");
ajaxDiv.removeClass("d-none");
let id = $(this).data("id");
$.get('/cart/add/' + id, {}, function(data) {
$("div.smallcart").html(data);
ajaxDiv.find("img").addClass("d-none");
ajaxDiv.find("p").removeClass("d-none");
setTimeout(() => {
ajaxDiv.animate({
opacity: 0
}, function() {
$(this).addClass("d-none").fadeTo(.1, 1);
$(this).find("img").removeClass("d-none");
$(this).find("p").addClass("d-none");
});
});
});
});
});
</script>
}
Try this
#If(Model!=null)
{
#foreach (var item in Model)
{
..........
<p>
#if (item.Quantity == 0) {
<a disabled class="btn btn-primary addToCart">Add to cart</a>
}
else
{
<a asp-controller="Cart" asp-action="Add" asp-route-id="#item.Id" data-id="#item.Id" id="addToCartButton" class="btn btn-primary addToCart">Add to cart</a>
}
</p>
}
}

mvc) I wanna get list of player in my listplayer view

namespace Seoyoung_K_301000618.Model
{
public class Repository
{
private static List<Player> addplayers = new List<Player>();
public static IEnumerable<Player> Players
{
get
{
return addplayers;
}
}
public static void AddPlayer(Player player)
{
addplayers.Add(player);
}
}
}
I have an error >> InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Seoyoung_K_301000618.Model.Player', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[Seoyoung_K_301000618.Model.Player]'.
I want to add player name and ID in listplayer view but I can't.
I want to fix my code like if player choose "Yes, I will", the player name and ID will be added to listplayer.
Here is my "manage" code (join page)
#model Seoyoung_K_301000618.Model.Player
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Join us</title>
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.min.css" />
<link href="~/css/style.css" rel="stylesheet" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-md navbar-cheerful fixed-top bg-dark">
<a class="navbar-brand disabled" href="/Home/Index">
<img src="~/images/logo.png" width="50" height="50" />
</a>
<button class="navbar-toggler" type="button"
data-toggle="collapse" data-target="#navbarCollapse" id="btnNavigation"
aria-expanded="false">
<i class="fa fa-caret-down" style="color:#feb0cc"></i>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto" style="text-align:center">
<li class="nav-item active">
<a class="nav-link" href="/Home/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/Home/club">More Information</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/Home/Manage">Join</a>
</li>
</ul>
</div>
</nav>
</header>
<main role="main">
<div class="album py-5">
<div class="container">
<div class="col-md-12">
<div class="col-md-4"> </div>
<div class="col-md-4"> </div>
<h1>Join us!</h1>
<hr />
<form class="p-a-l" asp-action="RsvpForm" method="Post">
<div asp-validation-summary="All"></div>
<div class="form-group">
<label asp-for="Name">Your name:</label>
<input class="form-control" asp-for="Name" />
</div>
<div class="form-group">
<label asp-for="Email">Your ID</label>
<input class="form-control" asp-for="Email" />
</div>
<div class="form-group">
<label asp-for="Phone">Your Password</label>
<input class="form-control" asp-for="Phone" />
</div>
<div class="form-group">
<label asp-for="WillJoin">Will you join?</label>
<select class="form-control" asp-for="WillAttend">
<option value="">Choose an option</option>
<option value="true">Yes, I want</option>
<option value="false">No, I don't want</option>
</select>
</div>
<div class="text-center">
<button class="btn btn-primary" type="submit">Register</button>
</div>
</form>
</div>
</div>
</div>
</main>
<footer class="container">
<p>© 2020 Seoyoung - Centennial College - COMP229.</p>
</footer>
<script src="~/js/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="~/js/jquery.min.js"><\/script>')</script>
<script src="~/lib/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Here is my Homecontroller code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Seoyoung_K_301000618.Model;
namespace Seoyoung_K_301000618.Controllers
{
public class HomeController : Controller
{
[HttpPost]
public ViewResult Manage(Player player)
{
if (ModelState.IsValid)
{
Repository.AddPlayer(player);
return View("ListPlayer", player);
}
else
{
return View();
}
}
[HttpGet]
public ViewResult Manage()
{
return View();
}
public ViewResult ListPlayer()
{
return View(Repository.Players.Where(r => r.WillJoin == true));
}
public ViewResult Index()
{
return View();
}
public ViewResult Club()
{
return View();
}
}
}
And, Here is my listplayer code (the player information will be added here)
#model IEnumerable<Seoyoung_K_301000618.Model.Player>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>List of Player</title>
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.min.css" />
<link href="~/css/style.css" rel="stylesheet" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-md navbar-cheerful fixed-top bg-dark">
<a class="navbar-brand disabled" href="/Home/Index">
<img src="~/images/logo.png" width="50" height="50" />
</a>
<button class="navbar-toggler" type="button"
data-toggle="collapse" data-target="#navbarCollapse" id="btnNavigation"
aria-expanded="false">
<i class="fa fa-caret-down" style="color:#feb0cc"></i>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto" style="text-align:center">
<li class="nav-item active">
<a class="nav-link" href="/Home/Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/Home/club">More Information</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/Home/Manage">Join</a>
</li>
</ul>
</div>
</nav>
</header>
<main role="main">
<div class="album py-5">
<div class="container">
<div class="col-md-12">
<div class="col-md-4"> </div>
<div class="col-md-4"> </div>
<h1>Here is the list of player</h1>
<hr />
</div>
</div>
<table class="table table-sm table-striped table-bordered">
<thead>
<tr>
<tr>
<th>Name</th>
<th>ID</th>
</tr>
</thead>
<tbody>
#foreach (Seoyoung_K_301000618.Model.Player addplayers in Model)
{
<tr>
<td>#addplayers.Name</td>
<td>#addplayers.Id</td>
</tr>
}
</tbody>
</table>
</div>
</main>
<footer class="container">
<p>© 2020 Seoyoung - Centennial College - COMP229.</p>
</footer>
<script src="~/js/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="~/js/jquery.min.js"><\/script>')</script>
<script src="~/lib/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
The listplayer view looks like that
namespace Seoyoung_K_301000618.Model
{
public class Repository
{
private static List<Player> addplayers = new List<Player>();
public static IEnumerable<Player> Players
{
get
{
return addplayers;
}
}
public static void AddPlayer(Player player)
{
addplayers.Add(player);
}
}
}
You made a mistake here
if (ModelState.IsValid)
{
Repository.AddPlayer(player);
//you have return single player object
return View("ListPlayer", player);
}
Right Code
if (ModelState.IsValid)
{
Repository.AddPlayer(player);
Repository.SaveChanges();
return RedirectToAction("ListPlayer");
}

jquery / Ajax "undefined" error

i am trying to get an image uploader working inside my MVC project, but everytime i click the upload file button, i get "Error undefined", i am not sure where i am going wrong.
The page is a partial view, loaded inside a #Html.BeginForm . below is the code i am using.
Index.cshtml
#using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="container">
<div class="row">
<article class="col-sm-12 col-md-12 col-lg-12 sortable-grid ui-sortable">
<div id="wid-id-0">
<!-- widget div-->
<div role="content">
<!-- widget content -->
<div class="widget-body">
<div class="row" style="background: white">
<form id="wizard-1" novalidate="novalidate">
<div id="bootstrap-wizard-1" class="col-sm-12">
<div class="tab-content">
#*Tab 1 (Step 1)*#
<div class="tab-pane active" id="tab1">
<br>
#Html.Partial("Registration/_Step1")
<div class="form-actions">
<div class="row">
<div class="col-sm-12">
<ul class="pager wizard no-margin">
<li class="previous disabled">
Previous
</li>
<li data-target="#step2" class="next">
Next
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="form-bootstrapWizard">
<ul class="bootstrapWizard form-wizard" style="background: coral">
<li class="active" data-target="#step1">
<span class="step">1</span> <span class="title">Step 1: Profile Information</span>
</li>
<li data-target="#step2" class="">
<span class="step">2</span> <span class="title">Step 2: Profile Picture</span>
</li>
<li data-target="#step3" class="">
<span class="step">3</span> <span class="title">Step 3: Identification</span>
</li>
<li data-target="#step4">
<span class="step">4</span> <span class="title">Step 4: Submit Profile</span>
</li>
</ul>
<div class="clearfix"></div>
</div>
</div>
</form>
</div>
</div>
<!-- end widget content -->
</div>
<!-- end widget div -->
</div>
<!-- end widget -->
</article>
</div>
</div>
}
_Step1.cshtml
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++)
{
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: "POST",
url: '#Url.Action("UploadFiles", "Account")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("error: " + error.statusMessage);
}
});
});
});
</script>
<table align="center">
<tr>
<td style="text-align: center;"><label>Upload Profile Picture</label></td>
<td></td>
</tr>
<tr>
<td valign="top"><img id="imgPreview" src="~/Content/Images/upload_holder.PNG" class="img-holder" style="width: 180px; height: 180px;" /></td>
<td>
#*<input type="submit" class="btn btn-lg" style="width: 200px; background: #0091d9; color: white;" value="Upload Photo" />*#
#*<input id="input-4" name="input4[]" type="file" multiple class="file-loading" style="width: 200px; background: #0091d9; color: white;" value="Upload Photo">*#
<input type="file" id="FileUpload" multiple />
<input type="submit" id="Upload" value="Upload"/>
<br />
<br />
<label>Acceptable file formats: jpg, gif or png file</label>
<br />
<label>Under 1 MB</label>
</td>
</tr>
</table>
any help is greatly appreciated!
EdIT: Below is the controller function, but its never hit.
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

visual studio 2015, resharper, razor and formatting embedded html

I am running visual studio 2015 with resharper with an mvc application. I have a View in which I want to create a set of nested div tags, a la:
<div>
<label>...
<div>
<label>...
<label>...
<label>...
</div>
<div>
<div>
<label>...
<label>...
</div>
<label>...
<label>...
</div>
</div>
I have code like
<div class="content">
#{
var count = 0;
var depthList = new Stack<int>();
<text>
<div class="NestedSelect">
</text>
foreach (var category in Model.OrderBy(m => m.LeftLink)) {
if (depthList.Count == 0) {
depthList.Push(category.Depth);
<text>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
} else if (category.Depth > depthList.Peek()) {
depthList.Push(category.Depth);
<text>
<div>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
} else if (category.Depth == depthList.Peek()) {
<text>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
} else {
while (category.Depth < depthList.Peek()) {
depthList.Pop();
//####
<text>
</div>
</text>
}
<text>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
}
//####
<text>
</div>
</text>
count++;
if (count == 0) {
}
}
}
</div>
EDIT
Notice the wonky <text></div></text> blocks (marked with //####) inside the loop. VS and/or resharper are very put out that my closing div tags do not seem to have mates. The opening <text> tags are highlighted in the editor but the ending </text> tags are not. They have an error underline and the tooltip "End tag is missing matching start tag".
I have tried using the #: constructs but when the code is formatted it puts the #: on a line by itself and then gets confused with the naked html tags.
How does one build nested html structures with this?
The #: construct should be used here as you suggested,but only on the tags that are causing the issue.
try something like this:
<div class="content">
#{
var count = 0;
var depthList = new Stack<int>();
<text>
<div class="NestedSelect">
</text>
foreach (var category in Model.OrderBy(m => m.LeftLink))
{
if (depthList.Count == 0)
{
depthList.Push(category.Depth);
<text>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
}
else if (category.Depth > depthList.Peek())
{
depthList.Push(category.Depth);
#:<div>
<text>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
}
else if (category.Depth == depthList.Peek())
{
<text>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
}
else
{
while (category.Depth < depthList.Peek())
{
depthList.Pop();
#:</div>
}
<text>
<label>
<input type="radio" name="categories" value="#category.Id"><span>#category.Name</span>
</label>
</text>
}
#:</div>
count++;
if (count == 0)
{
}
}
}
You should use #: construct if you are not obsessed with formatting.
#: </div>
If you are, consider using WriteLiteral :
WriteLiteral("</div>");

System.NullReferenceException on direct navigation to page

Hi I have a problem when I try to access a page in my application directly. When I navigate within the application to the page, does everything work.
<input type="button"
class="btn btn-primary"
id="calulate"
value="Finanzierungsrate berechnen"
onclick="location.href ='#Url.Action("calculate", "RatesKit", new { id = "bc338d8d-58b9-4867-9730-6b92a516a496"}) '" />
Here the controller method:
[HttpGet]
public ActionResult calculate(string id, string objectDescription, string objectPrice)
{
if (string.IsNullOrEmpty(id))
{
return RedirectToAction("NotValid");
}
else
{
if (Validator.ValidateToken(id, out bob))
{
OfferRequest request = Session["RequestOffer"] as OfferRequest;
if (request != null)
{
ViewData["Dealer"] = bob;
//..
}
}
else
{
return RedirectToAction("NotValid");
}
return View();
}
}
when I reload the page with F5, the page loaded without Problems. But if I try to access the site directly (Just hit enter in the address bar of Browser), I get the following error message:
Definitely, theres is no mistake at this point! If I remove the Razor Syntax #DateTime.Now.Year the fault is located at a different point with Razor syntax.
I do not know, why there is an error only with direct access.
Similar problems I've already looked at, unfortunately without solution to my problem.
System.NullReference Exception occurred in App_Web_XXX.dll - Error in Partial View
System.NullReferenceException in App_Web_*.dll
Thanks for any advice
Her the full page:
#{
ViewBag.Title = "Finanzierungsrate berechnen";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<meta charset="utf-8" />
<div align="center">
<h2>Finanzierungsrate berechnen</h2>
<div style="max-width:700px;">
<div id="ratesView">
#{Html.RenderPartial("ViewCalculateRate", ViewData);}
</div>
</div>
</div>
<table>
<tr>
<td valign="top" class="footerContent" style="padding-top: 20px;color: #878780; font-size: 11px; text-align: left;">
© #DateTime.Now.Year XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Alle Rechte vorbehalten. Impressum
</td>
</tr>
<tr valign="top" class="footerContent" style="padding-top: 20px; color: #878780; font-size: 11px; text-align: left;">
<td>Wir übernehmen keine Gewähr für die Richtigkeit dieser Berechnung.</td>
</tr>
</table>
<div id="backbutton" style="padding:20px 0; display:inline-block;">
<input type="button"
class="btn btn-primary btn-xs"
id="backButton"
value="Zurück"
onclick="location.href ='#Request.UrlReferrer.AbsoluteUri'" />
</div>
I got it....
<div id="backbutton" style="padding:20px 0; display:inline-block;">
<input type="button"
class="btn btn-primary btn-xs"
id="backButton"
value="Zurück"
onclick="location.href ='#Request.UrlReferrer.AbsoluteUri'" />
</div>
Request does not exist when I go directly to the page. So I was unable to create the button ...
THX Sometimes you have to look at the code times from the outside.

Resources