ASP.NET MVC Ajax example by Scott Allen isn't working - asp.net

i am watching videos of Scott Allen at pluralsight site, exactly I am talking about this module :
AJAX:
So i created exactly the same example as shown at video, but it is not working, I have no idea why and spent an hour looking for this, here is my code:
At BoundleConfig.cs file:
bundles.Add(new ScriptBundle("~/bundles/otf").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Scripts/jquery.validate*"
));
At Web.config file in appSettings section I added:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
And here we go:
public ActionResult Review(string searchString)
{
var model = _repository.StartDs;
if (!String.IsNullOrEmpty(searchString))
{
model = model.Where(x => x.FirstName.Contains(searchString));
}
if (Request.IsAjaxRequest())
{
return PartialView("_Review", model);
}
return View(model);
}
Review.cshtml file :
#model IEnumerable<nauka.Models.StartData>
#using(Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "girlsList"
}))
{
<input type="search" name="searchString"/>
<input type="submit" value="Znajdź" />
}
#Html.Partial("_Review", Model)
_Review.cshtml file:
#model IEnumerable<nauka.Models.StartData>
<div id="girlsList">
<table style="width:100%">
<tr>
<th>ID</th>
<th>Imię</th>
<th>Nazwisko</th>
<th>Wzrost</th>
<th>Rozmiar</th>
<th>Akcje</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.Height</td>
<td>#item.TitsSize</td>
<td>#Html.ActionLink("Usuń", "Delete", new { id = item.Id })</td>
</tr>
}
</table>
</div>
I checked it, this fragment at my action method :
if (Request.IsAjaxRequest())
{
return PartialView("_Review", model);
}
never execute, which means that a request isn't recognized as an AjaxRequest, the question is why? I edited this line and pasted
return View("Index");
so it shloud redirect me to my Index site, but it didn't so i proved that AjaxRequest is not executed. I have no idea, what is missing here, I did exactly as at video shown.
Above my _Layout.cshtml file which is autmatically added to every view page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
<li>#Html.ActionLink("Dodaj", "Add", "Home")</li>
<li>#Html.ActionLink("Przegladaj", "Review", "Home")</li>
<li>#Html.ActionLink("Filtruj", "FilterTest", "Home")</li>
</ul>
#Html.Partial("_LoginPartial")
</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/otf")
#RenderSection("scripts", required: false)
</body>
</html>

Ough... solved!!
I didn't add a
jquery.unobtrusive-ajax.min.js library to my solution through NuGet package installer.
But when I added this before to BoudleConfig ( path
"~/Scripts/jquery.unobtrusive-ajax.min.js",), why it didn't shout that this library isn't present at my project in Visual ??!
It made many complications..

Related

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts" Login/Register

so I have this weird problem, and honestly I have no clue when it stopped working, so it's hard for me to understand where's the problem. Basically, the login and register buttons stopped working, and I have no clue why.
From reading the error I understand that the problem is somewhere in the _Layout.cshtml, because I didn't touch the _LoginPartial.cshtml or any other related files in that matter.
Here's my _Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Guitar Store</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Guitar Store", "List", "Product", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "List", "Product")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
<li>#Html.Action("Summary", "Cart")</li>
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
</div>
<br /><br /><br />
<div class="row panel">
<div id="categories" class="col-lg-3">
#Html.Action("Menu", "Nav")
</div>
<div class="col-lg-7">#RenderBody()</div>
</div>
</body>
</html>
Could you please guide me to fixing that problem?
Edit: If any more files are needed I can edit them inside here.
Okay, I found out what the problem was. I removed
#RenderSection("scripts", required: false)
from the _Layout.cshtml body. Apparently you have to have that in order for the login and register to work.

ASP.NET MVC is it possible to use ajax.beginform inside a partial view?

Layout -> View -> Partial View
In the View:
<div class="col-md-8">
#{Html.RenderPartial("_komentari", commentlist);}
<div class="gap gap-small"></div>
<div class="box bg-gray">
<h3>#Res.commentwrite_title</h3>
#using (Ajax.BeginForm("postcomment", new { propertyid = Model.PublicID }, new AjaxOptions { UpdateTargetId = "commentsarea", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>#Res.commentwrite_content</label>
<textarea id="comment" name="comment" class="form-control" rows="6"></textarea>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value='#Res.commentwrite_btn' />
</div>
</div>
</div>
}
</div>
</div>
In the Partial View:
<div id="commentsarea">
<ul class="booking-item-reviews list">
#if (Model != null)
{
foreach (Comment item in Model)
{
<li>
<div class="row">
<div class="col-md-2">
<div class="booking-item-review-person">
<a class="booking-item-review-person-avatar round" href="#">
<img src="/assets/img/70x70.png" alt="Image Alternative text" title="Bubbles" />
</a>
<p class="booking-item-review-person-name">
#if (item.UserId != null)
{
<a href='#Url.Action("details", "user", new { userid = item.User.PublicId })'>#item.User.Username</a>
}
else
{
Anonymous
}
</p>
</div>
</div>
<div class="col-md-10">
<div class="booking-item-review-content">
<p>
#item.Content
</p>
<p class="text-small mt20">#item.DateOnMarket</p>
<p class="booking-item-review-rate">
#using (Ajax.BeginForm("reportcomment", new { comment = item.PublicId }, new AjaxOptions { UpdateTargetId = "reportscount", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, null))
{
<a id="submit_link" href="#">Spam?</a>
<a class="fa fa-thumbs-o-down box-icon-inline round" href="#"></a>
}
<b id="reportscount" class="text-color">#item.CommentReports.Count</b>
</p>
</div>
</div>
</div>
</li>
}
}
</ul>
</div>
<script>
$(function () {
$('a#submit_link').click(function () {
$(this).closest("form").submit();
});
});
</script>
View
Both scripts for Ajax are always included in the Layout (I'm already using Ajax on other pages too). On the View page, when I add a new comment, it is added in the database and shows the updated list of comments via ajax. Everything works fine.
Partial View
But if I want to report the comment as spam, I have to click on the link inside the Partial View (#submit_link), and after reporting, inside the #reportscount part, I want to show the updated number of reports of that comment. The actionresults returns that number like Content(numberofreports.toString()). It works but I get the number in a blank page?
Thank you very much.
It's better if you don't. The main issue is that, for security reasons, <script> tags are ignored, when HTML is inserted into the DOM. Since the Ajax.* family of helpers work by inserting <script> tags in place, when you return the partial via AJAX, those will not be present. It's better if you only include the HTML contents of the form in the partial, and not the form itself.

Asp.net - Javascript does not work on an iframe containing MVC view

I've created a view to display a "qlikview" document inside an iframe. Iframe prevents any javascript execution when the mentioned view called from a controller. If I remove the iframe js works fine.
Iframe works ok but js not. What would be the reason of this?
Thanks.
My View:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
<iframe id="qlikFrame" src="#ViewBag.IframeLink" style="width:100%; height:768px" frameborder="0" scrolling="no" />
</div>
_Layout:
$(document).ready(function() {
alert("you clicked the paragraph");
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css") #Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Home", "Index", "Home", null, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
#if (#Request.IsAuthenticated) {
<li class="dropdown">
<a href="#" id="dropdown-item" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Dashboards
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>#Html.ActionLink("SD", "Document", "Dashboard", new { Id = SD" }, null)</li>
} #if (Request.IsAuthenticated && User.IsInRole("Admin")) {
<li>#Html.ActionLink("RolesAdmin", "Index", "RolesAdmin")</li>
<li>#Html.ActionLink("UsersAdmin", "Index", "UsersAdmin")</li>
}
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
</div>
#Scripts.Render("~/bundles/jquery") #Scripts.Render("~/bundles/bootstrap") #RenderSection("scripts", required: false)
</body>
</html>
This was because of a strange behaviour of vs2015 or MVC, not sure which one.
The problem is about iframe closure tag:
if I write <iframe></iframe> Js works, but if I write <iframe /> Js doesn't work.
In a webform project in vwd2010, I've used the latter syntax, iframe and Js worked without any problem.
If anyone meets this misbehaviour, above might be the resolution.

ASP.NET MVC refresh table in tab-pill

I have a problem with my solution.
I have 2 related classes and display them like the example on the ASP.net -Webseite, but only with one related class.
This class is displayed in a tab-pill.
Now I added Modals and a Javascript to edit, delete and create new Entitys, like This., but i don't know how to implement the refresh function, that only my table from the related class refresh and not the page. I will not lose the tab-pill, with is activated.
Thanks for help
Here my View-Page:
#model Armageddon.Models.itUser
#{
ViewBag.Title = "Details ";
}
#using Armageddon.Helpers;
<h2>Details:</h2>
<div>
<hr />
<div class="col-md-5" style="text-align:right">#Html.LabelFor(model => model.displayName)</div>
<div class="col-md-5">#Html.DisplayFor(model => model.displayName)</div>
</div>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
<ul class="nav nav-tabs" role="tablist" id="myTab">
<li role="presentation" class="active">Logins</li>
</ul>
<div class="tab-content">
<div role="tabpanel" class="tab-pane" id="UIT2SysGroup">
#if (Model.UIT2SystemGroup != null)
{
<table class="table">
<tr>
<th>Gruppen</th>
<th>#Html.NoEncodeActionLink("<span class='glyphicon glyphicon-plus'></span>", "Add", "Create", "UIT2SystemGroup", routeValues: new { PersonId = Model.itUserID }, htmlAttributes: new { data_modal = "", #class = "btn btn-primary pull-right" })</th>
</tr>
#if (Model.UIT2SystemGroup.Count() != 0)
{
foreach (var item in Model.UIT2SystemGroup)
{
<tr>
<td>
#item.SystemGroup.Name
</td>
<td>
<div class="pull-right">
#Html.NoEncodeActionLink("<span class='glyphicon glyphicon-trash'></span>", "Delete", "Delete", "UIT2SystemGroup", routeValues: new { id = item.UIT2SystemGroupID}, htmlAttributes: new { data_modal = "", #class = "btn btn-danger" })
</div>
</td>
</tr>
}
}
else
{
<tr><td colspan="3"><div class="alert alert-info" role="alert"><div class="glyphicon glyphicon-info-sign"></div> Zurzeit sind keine administrativen Aufgaben vergeben.</div></td></tr>
}
</table>
}
</div>
</div>
You need to look into Ajax to call the controller that is returning the view.
There is a good sample here
http://www.c-sharpcorner.com/UploadFile/d551d3/how-to-load-partial-views-in-Asp-Net-mvc-using-jquery-ajax/
You could put your table inside a partial view and return this as part of your page.

angular $resource save function is not mapping with dataannotation

I am new to angular. And I am creating a practice project. I am following This tutorial.
Everything is working fine except when I try to put data annotations in my View Model the $resource.save method no more works. Without data annotations, it works fine.
Here is my code:
Home.html:
<!DOCTYPE html>
<html ng-app="movieModule">
<head>
<meta name="viewport" charset="UTF-8" content="width=device-width, initial-scale=1">
<title>Movie Sample</title>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../Scripts/angular.min.js"></script>
<script src="../Scripts/angular-resource.min.js"></script>
<script src="../Scripts/angular-route.min.js"></script>
<script src="../Scripts/jquery-2.1.1.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<script src="../Scripts/movie-module.js"></script>
<script src="../Scripts/Category/category-controller.js"></script>
<script type="text/javascript">
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href") // activated tab
});
</script>
</head>
<body>
<div class="container">
<div class="container-fluid">
<div class="well">
<ul class="nav nav-pills">
<li role="presentation" class="active">Home</li>
<li role="presentation">Movies</li>
<li role="presentation">Categories</li>
<li role="presentation">Artists</li>
</ul>
</div>
</div>
<div class="container-fluid">
<div ng-view="">
</div>
</div>
</div>
</body>
</html>
Categories.html:
<div>
<a href="create-category.html" class="btn btn-primary">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</a>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Categories</div>
<!-- Table -->
<table class="table">
<tr>
<th>ID
</th>
<th>Name
</th>
<th>Description
</th>
</tr>
<tr data-ng-repeat="category in categories">
<td>{{ category.id }}
</td>
<td>{{ category.name }}
</td>
<td>{{ category.description }}
</td>
</tr>
</table>
</div>
create-category.html
<div class="row">
<div class="col-md-12">
<h3>Create Category
</h3>
</div>
</div>
<!--<div class="row">-->
<div class="col-md-12">
<div class="form-group">
<label for="id">Id:</label>
<input type="text" ng-model="category.Id" class="form-control">
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" ng-model="category.Name" class="form-control">
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" ng-model="category.Description" class="form-control">
</div>
<button type="submit" class="btn btn-primary" ng-click="save(category)">Create Category</button>
</div>
movieModule.js
var movieModule = angular.module('movieModule', ['ngRoute', 'ngResource']);
movieModule.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/templates/categories.html', { templateUrl: '/templates/categories.html', controller: 'categoryController' }).
when('/templates/create-category.html', { templateUrl: '/templates/create-category.html', controller: 'categoryController' });
$locationProvider.html5Mode(true);
});
category-controller.js
movieModule.controller('categoryController', function ($scope, $resource, $location) {
$scope.categories = $resource('/api/Category').query();
$scope.save = function (category) {
$scope.errors = [];
$resource('/api/Category').save(category).$promise.then(
function () { $location.url('templates/categories.html'); },
function (response) {
$scope.errors = response.data;
});
}
});
CategoryVM.cs
public class CategoryVM
{
[Required(ErrorMessage="Is is required.")]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
The problem is [Required(ErrorMessage="Is is required.")]. Everything works fine without [Required(ErrorMessage="Is is required.")]but the moment I put [Required(ErrorMessage="Is is required.")] it starts giving error:
Here is the snapshot of the error:
Try not to put the [Required] attribute on the Id.
It should work if you put data annotations on your other properties.
[Required] to a value type (int) will cause a 500 error
(string is not a value type)

Resources