ASP is not defined at #ko.Apply(Model) - asp.net-mvc

I m trying to bind my model and get error
Uncaught ReferenceError: Unable to process binding "value: function (){return ASP._Page_Views_Configuration_Index_cshtml.Model().SomeProperty }"
Message: ASP is not defined
View:
#using PerpetuumSoft.Knockout
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/knockout")
#model Asteros.MKD.Controllers.SomeModel
#{
var ko = Html.CreateKnockoutContext();
}
#ko.Html.TextBox(model => Model.SomeProperty)
#ko.Apply(Model)
bundles:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
....
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-{version}.js",
"~/Scripts/knockout.mapping-latest.js",
"~/Scripts/perpetuum.knockout.js"
));
Any ideas?

Use model instead of Model:
#ko.Html.TextBox(model => model.SomeProperty)

Related

Jquery-UI control not showing in MVC

I am a newb in using jquery in MVC, please bear with me. I cannot seem to display the jquery-ui slider control in my mvc page. I have tried to implement the following articles which I have found on the web:
How to add jQueryUI library in MVC 5 project?
jQuery UI with MVC 4
JQuery UI datepicker in Asp.Net MVC
http://blog.falafel.com/three-steps-use-jquery-ui-asp-net-mvc-5/
However, when I run the code, nothing shows. I have created a small little test project, and am trying to implement the slider on the about page. Here is my code:
In the About.cshtml:
#{
ViewBag.Title = "About";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
<div style="border: none; height: 20px;" id="slider">
</div>
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#slider").slider();
});
</script>
}
In the BundleConfig.cs file:
using System.Web;
using System.Web.Optimization;
namespace TestApp
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-1.10.2.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-1.11.4.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery-ui.css",
"~/Content/themes/base/jquery-ui.all.css"
//"~/Content/themes/base/jquery.ui.core.css",
//"~/Content/themes/base/jquery.ui.resizable.css",
//"~/Content/themes/base/jquery.ui.selectable.css",
//"~/Content/themes/base/jquery.ui.accordion.css",
//"~/Content/themes/base/jquery.ui.autocomplete.css",
//"~/Content/themes/base/jquery.ui.button.css",
//"~/Content/themes/base/jquery.ui.dialog.css",
//"~/Content/themes/base/jquery.ui.slider.css",
//"~/Content/themes/base/jquery.ui.tabs.css",
//"~/Content/themes/base/jquery.ui.datepicker.css",
//"~/Content/themes/base/jquery.ui.progressbar.css",
//"~/Content/themes/base/jquery.ui.theme.css"
));
}
}
}
In the Global.asax.cs file:
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace TestApp
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
and in the _Layout.cshtml file:
<!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>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#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>
</ul>
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Styles.Render("~/Content/themes/base/css")
#RenderSection("scripts", required: false)
</body>
</html>
I have also created a screenshot of my Solution Explorer in case it may help:
Solution Explorer screenshot
I think it must be something small, but I am struggling to find the problem. I would appreciate it if anyone can point out what I should change in order to see and use the jquery-ui slider, or any other jquery controls in my site.
I found my mistake. I did not add/include the Jquery-ui.css file in the content folder. Once it was included I could see the Jquery control.
The link below explained and helped a lot in finding my mistake:
asp-net-mvc-4-jquery-datepicker
Hopefully this post can help someone else too.

MVC 4 Using Paged List in a partial View

I am trying to implement PagedList in a partial view.
Describing the view setup. I have Controller A with ViewA. This is the parent view and has its own model. Then I have Controller B with PartialViewB and has its own model as well. Then I have a Div in ViewA that will be used to display the PartialViewB. I can load in PartialViewB after hitting a button and then hide the view after hitting the button again. Within the PartialViewB is the PagedList. Hitting the next page button loads the next page, but loads it in its own page, not in the ViewA as it was before.
I can load up more code as needed, but for now here is the Pager
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ViewComments",
new { courseID = #ViewBag.courseID, page }),
new PagedListRenderOptions { MaximumPageNumbersToDisplay = 5, DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded })
::EDIT::
Parent View
<div class="Comments">
<input type="button" id="View" class="CommentsButton" value="View Comments"/>
<input type="hidden" id="Hidden" value="false" />
</div>
<div id="Comments">
</div>
PartialView
#model PagedList.IPagedList<QIEducationWebApp.Models.CourseComment>
#using PagedList.Mvc;
#{
ViewBag.Title = "Comments";
}
<h2>Comments!</h2>
<table>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CommentDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
#Html.DisplayFor(modelItem => item.CommentText)
</td>
</tr>
}
</table>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ViewComments",
new { courseID = #ViewBag.courseID, page }),
PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new PagedListRenderOptions { MaximumPageNumbersToDisplay = 5, DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded,
DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded },
new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "Comments" }))
BundleConfig.cs
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css", "~/Content/PagedList.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
Check this out: Related SO question
This will use unobtrusive ajax to do the replace for you. You just need to handle the fetch and skip on your end and send back the new partial view along with the model.
#Html.PagedListPager(Model, page => Url.Action("ViewComments", page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing( new AjaxOptions(){ HttpMethod = "GET", UpdateTargetId = "partialContainerYouNeedToReplace"}))
Make sure that you have unobtrusive js referenced on your page when doing this. It comes with MVC out of the box and you should just need to reference the bundle.
Hope this helps.

ASP.NET MVC and AngularJS

I am using AngularJS 1.2.2 (and am totally new to it) and MVC 5. I am trying to get a controller get called but it is not working.
As far as I could tell, the most appropriate 'shell' page is Views/Shared/_Layout.cshtml.
Therefore, in this page I have
<html data-ng-app="myApp">
Latter on in the Views/Shared/_Layout.cshtml I have
<div class="navbar navbar-fixed-top">
<div class="container">
<ul class="nav nav-pills" data-ng-controller="NavbarController">
<li data-ng-class="{'active':getClass('/home')}">Home</li>
<li data-ng-class="{'active':getClass('/albums')}">Albums</li>
</ul>
</div>
</div>
But when I click on either of these two links my getClass method does not get called. The file containing this method is being refernced. Here is the code it contains
app.controller('NavbarController', function ($scope, $location) {
$scope.getClass = function(path) {
if ($location.path().substr(0, path.length) == path) {
return true;
} else {
return false;
}
};
});
Any idea why this is not being called?
EDIT
My structure is such:
I have an app folder in the root.
In the app folder I have an app.js with this code
var app = angular.module('myApp', []);
app.config(function ($routeProvider) {
$routeProvider
.when('/Home',
{
controller: 'HomeController',
templateUrl: '/Views/Home/Index.cshtml'
})
.when('/Album',
{
controller: 'AlbumController',
templateUrl: '/View/Album/Index.cshtml'
})
.otherwise({ redirectTo: '/Home' });
});
(Incidentally I am guessing that by referring to my individual cshtml files like this I will get the correct behavior).
I have a controllers folder with the above NavbarController class.
I also have a services folder with my services in them.
In the _Layout file I have these js files referenced
#Scripts.Render("~/Scripts/angular.js")
#Scripts.Render("~/Scripts/angular-route.js")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
#Scripts.Render("~/app/app.js")
#Scripts.Render("~/app/controllers/navbarController.js")
#Scripts.Render("~/app/controllers/albumController.js")
#Scripts.Render("~/app/services/albumService.js")
There is an error in the console. It is
Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:unpr] Unknown provider: $routeProvider http://errors.angularjs.org/1.2.2/$injector/unpr?p0=%24routeProvider ...
It looks like you missed to include the ngRoute module in your dependency for myApp.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
//Your code
}]);

javascript validate not working in mvc app

In my MVC4 app, I'm trying to create a client side validator for some textboxes in a form. The form is contained in the Register.cshtml view (this view is automatically created by VS2010 when i make a new MVC4 with formsauthentication project).
The form already implements validation on Submit button, but I want a validator that acts as soon as focus leaves the textbox - should show me an inline error just next to the textbox, with a red font. if it validated ok, it should again show the message 'ok'.
The problem: The .js validator doesn't work. Firebug says:
$document is not defined.
$document.ready(
I also tried alert(), if i place it outside the document.ready function, it pops. when inside, it doesnt pop.
Code for registerForm.js:
$document.ready(
function ()
{
$('#registration form').validate
(
{
rules:
{
UserName: { required: true }
},
success: function (label)
{
label.Text('OK!').addClass('IsInputValid');
}
}
)
}
);
The bundle that adds this javascript is as follows:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/registerForm.js",
"~/Scripts/jquery.validate*"));
Finally, the view:
<div id="registration">
#using (Html.BeginForm()) {
#Html.ValidationSummary()
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
#Html.LabelFor(m => m.UserName)
#Html.TextBoxFor(m => m.UserName)
</li>
<li>
#Html.LabelFor(m => m.Email)
#Html.TextBoxFor(m => m.Email)
</li>
<li>
#Html.LabelFor(m => m.Password)
#Html.PasswordFor(m => m.Password)
</li>
<li>
#Html.LabelFor(m => m.ConfirmPassword)
#Html.PasswordFor(m => m.ConfirmPassword)
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
What could prevent the js from working?
I've already spent about 5hours trying to figure this out. Please let me know if you have any suggestions,
Regards,
#Html.TextBoxFor(m => m.UserName, new { #class = "required" })
No need for JS here. And what everyone else is saying about $document not being the correct syntax, unless you have var $document = $(document) defined somewhere.
You should use jQuery wrapper for document object:
$(document).ready(function () {
// your function
});
Is $document defined? jQuery defines a $ object. You can use that object as a function and pass it a selector, including document, and call .ready() on that:
$(document).ready(someFunction);

Date picker in mvc3 with razor view engine

I am using mvc3 and razor is my view engine how i get date picker with out using scripts in my
view.
You can create a script in the directory scripts of your project.
Basic example:
$(document).ready(function () { $("#datepicker").datepicker({ });});
in your view:
#model YourProjectName.Models.User
....
<div class="editor-field">
#Html.TextBoxFor(model => model.Dateadd, new { #Value = DateTime.Now, id = "datepicker" })
#Html.ValidationMessageFor(model => model.Dateadd)
</div>
I think you are going to have to use a script, check out jqueryui datepicker. Its a nice easy to use library and supports theming
I answered here, check it out: http://forums.asp.net/post/4647234.aspx
Basically you're using a template with a script in one location and calling it with EditorFor.
To advisers here: it's a bad practice to use scripts inside partial views (templates).
In my case it does not work at all. Because accessing jquery happens before it's included as js file.
Plus you cannot predict where exactly you would put this datepicker control.
Also, you will have this "ready" block for every editor on the page.
RenderSection would bring some order to all this, but it does not work for partialviews and templates.
So just move javascript code from a template (partialview) to a view.
#model Nullable<System.DateTime>
#if ( Model.HasValue ) {
#Html.TextBox( "" , String.Format( "{0:yyyy-MM-dd HH:mm}" , Model.Value ) , new {
#class = "textbox" , #style = "width:400px;" } )
}
else {
#Html.TextBox( "" , String.Format( "{0:yyyy-MM-dd HH:mm}" , DateTime.Now ) , new {
#class = "textbox" , #style = "width:400px;" } )
}
#{
string name = ViewData.TemplateInfo.HtmlFieldPrefix;
string id = name.Replace( ".", "_" );
}
<script type="text/javascript">
$(document).ready(function () {
$("##id").datepicker
({
dateFormat: 'dd/mm/yy',
showStatus: true,
showWeeks: true,
highlightWeek: true,
numberOfMonths: 1,
showAnim: "scale",
showOptions: {
origin: ["top", "left"]
}
});
});
</script>
If you use an Editor Template for the DateTime type, you can use an HTML5 date picker (i.e. <input type="date" />). Essentially you put a view called DateTime.cshtml in a folder called Views/Shared/EditorTemplates, then you can style the editor however you like. One example is in an answer here.

Resources