I have the following extension method for jQuery to serialize Json called jquery.extension.js:
jQuery.fn.extend({
serializeJSON: function () {
return this.serializeArray().reduce(function (result, item) {
result[item.name] = item.value;
return result;
}, {});
}
});
And I have these references on my layout:
<script src="~/Content/Script/jquery.extensions.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.8.0.js" type="text/javascript"></script>
On my view I call the method like this:
function createList(e) {
var form = $(this),
dataJSON = serializeJSON(form),
$saveBtn = $('#create-list-btn');
But I'm getting the error:
ReferenceError: serializeJSON is not defined
Could anyone help me realize what is missing here?
I found the problem myself, the proper way to use it on the view is:
dataJSON = $(form).serializeJSON()
instead of:
dataJSON = serializeJSON(form)
Related
In my Net Core 2.1 MVC project I have a viewmodel parameter userID, that I want to assign to a JQuery variable after the page loads. The ID is not displayed anywhere on the page.
So far, this doesn't seem to work:
View:
#{int userID = Model.ID;}
// rest of html page.
#section scripts {
<script src="~/AssigntoVariable.js"></script>
}
AssignToVariable.js
$(document).ready(function () {
$(function () {
var json = userID;
console.log(json);
// removed further code
When I run this, I receive a 'UserID not defined' error, obviously.
How can I put the userID parameter from my viewmodel directly in a JQuery script?
You can access viewmodel parameter ID as userID on client-side like:
#section scripts {
<script type="text/javascript">
var userID = #(Html.Raw(Json.Encode(Model.ID)));
// You can now access userID here
console.log(userID);
</script>
<script src="~/AssigntoVariable.js"></script>
}
and now you can also access userID in AssignToVariable.js like:
$(document).ready(function () {
var json = userID;
console.log(json);
});
Please note that you don't need to use
$(document).ready(function () {
$(function () {
both of them in AssignToVariable.js file, as $(function () { is just a shorthand for $(document).ready(function () {. Please use either one of them.
Can somebody help in displaying webapi data in angularjs repeat directive in my first Angular application?
I'm getting data from the WEBAPI as expected like below
[{"FLAVOR_ID":"BES","FLAVOR_NAME":"BES"},{"FLAVOR_ID":"BUN","FLAVOR_NAME":"BUN"}]
API Controller:
public class ItemMaintenanceController : ApiController
{
ItemMaintenanceRepository itemRepository;
public ItemMaintenanceController(ItemMaintenanceRepository _itemRepository)
{
itemRepository = _itemRepository;
}
[HttpGet]
public IEnumerable<MA_Flavor> GetAllFlavors()
{
return itemRepository.GetAllFlavors();
}
}
Client.html:
<!DOCTYPE html>
<html>
<head>
<title> Client</title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<script>
alert("start");
var app = angular.module("myapp", ['ngResource']);
var controller = function ($scope, $resource) { // controller uses $resource, which is part of ngResource
$scope.flavor = {};
$scope.getFlavors = function () {
alert("calling getflvors");
var request = $resource("http://localhost:55762/api/ItemMaintenance/GetAllFlavors?Id=CMN");
$scope.flavor = request.query();
};
////$scope.clear = function () {
//// $scope.flavor = {};
//// $scope.error = "";
////}
$scope.getFlavors();
myapp.controller("ItemMaintenanceController", controller);
</script>
</head>
<body ng-app="contacts">
<div ng-controller="ItemMaintenanceController">
<select ng-model="flavor">
<option ng-repeat="fl in Flavor" value="{{fl.FLAVOR_NAME}}">{{fl.FLAVOR_NAME}}</option>
</select>
<h1>You selected: {{flavor.FLAVOR_NAME}}</h1>
</div>
</body>
</html>
Looks like issue with the names of the ng-controller, ng-module and ng-app. Try to change and hope it will work.
<body ng-app="contacts">
<div ng-controller="ItemMaintenanceController">
<Script>
var app = angular.module('contacts', []);
// To fetch all falvors
app.controller("ItemMaintenanceController", function ($scope, $http) {
.....
...
</script>
I think you're close. based on what you have I think something like this should work:
<select ng-model="selectedFlavorId">
<option ng-repeat="fl in flavor" value="{{fl.FLAVOR_ID}}">{{fl.FLAVOR_NAME}}</option>
</select>
your data is in $scope.flavor and I assume that if you debug it will look like this:
$scope.flavor = [{"FLAVOR_ID":"BES","FLAVOR_NAME":"BES"},{"FLAVOR_ID":"BUN","FLAVOR_NAME":"BUN"}]
you want the id in your value field as that is the bit you need to know which value you selected. the value you see in dropdown should be the name of the flavor.
when you select something, that value will be reflected in the model.
as I chose selectedFlavorId, you will find that populated under $scope.selectedFlavorId. Do not override your API data with the selected value like you've just done.
selectedFlavorId will give you the ID of the item you selected so you need a bit more code after this to get the name of that property from your data array.
There may following issues in your code.
Your angular modules defined as myapp and in ng-app you have used
contacts.
You have to create two different scope variables, one for the flavor
and another is flavors. flavors you need to use under the ng-options
and flavor you have to use for ng-model.
What I understood request.query() will return the resource object,
So have two options to get data from the query. More details about
the resource you can find here
var request = $resource("http://localhost:55762/api/ItemMaintenance/GetAllFlavors?Id=CMN");
Option 1
request.query(function(data) {
$scope.flavor = data;
});
Option 2
request.query().$promise.then(function(data) {
// success
$scope.flavor = data;
}, function(errResponse) {
// fail
});
I am trying to display Google Maps inside a Partial View with JSON. I have already tried the code inside a normal view and it works perfectly fine.
I have the following:-
Partial View ShowMap.cshtml
#using Microsoft.Web.Helpers
<script src="~/Scripts/jquery-1.8.3.min.js"></script>
<div class="experienceRestrictedText">
#Maps.GetGoogleHtml("1, Redmond Way, Redmond, WA", width: "400", height: "400")
</div>
Index.cshtml (where the Partial view is launched)
$('.modal_link_map').on('click', function (e) {
$('.modal_part').show();
var id = $(this).attr('data-id');
var context = $('#tn_select').load('/Experience/ShowMap?id=' + id, function () {
initSelect(context);
});
e.preventDefault();
return false;
});
And the controller Action is as follows:-
public ActionResult ShowMap()
{
_ItemID = Convert.ToInt32(Request.QueryString["id"]);
viewModel.ExperienceViewModel.Experience = unitOfWork.ExperienceRepository.GetByID(_ItemID);
return PartialView(viewModel);
}
Do I need to include anything else for this map to work?
I am not familiar with the #Maps.GetGoogleHtml helper but I am afraid that somehow this helper is including the following script:
<script src="//maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
Except that this script cannot be loaded asynchronously because it uses document.write() to load the actual API. To make this work you should specify a callback parameter. Here's how your partial could look like:
<div class="experienceRestrictedText">
<script src="//maps.google.com/maps/api/js?sensor=false&callback=initialize" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var map = new google.maps.Map(document.getElementById("map"), { zoom: 14, center: new google.maps.LatLng(47.652437, -122.132424), mapTypeId: google.maps.MapTypeId['ROADMAP'] });
new google.maps.Geocoder().geocode({ address: '1, Redmond Way, Redmond, WA' }, function (response, status) {
if (status === google.maps.GeocoderStatus.OK) {
var best = response[0].geometry.location;
map.panTo(best);
new google.maps.Marker({ map: map, position: best });
}
});
}
</script>
<div class="map" id="map" style="width:400px; height:400px;"></div>
</div>
Notice how a callback parameter is passed to the http://maps.google.com/maps/api/js script and the actual initialization of the maps is done inside this callback.
Also notice that I have removed the jquery script from the partial. I guess that jQuery is already loaded in your layout because you seem to be using it to attach to a .on() handler.
As an alternative you could have included the <script src="//maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> in your main view but once you load the partial, the
#Maps.GetGoogleHtml helper would have included it a second time.
Personally I am not a big fan of those kind of helpers because they are completely obscuring the underlying calls leaving you without much control and understanding of what's happening.
I've installed the Stack Exchange MiniProfiler, and View Source shows that it is rendering the expected HTML. However it does not show the little profile detail box in the corner - what could be wrong?
<script src="/v2/Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/v2/mini-profiler-includes.css?v=1.7.0.0">
<script type="text/javascript" src="/v2/mini-profiler-yepnope.1.0.1.js"></script>
<script type="text/javascript">
yepnope([
{ test: window.jQuery, nope: '/v2/mini-profiler-jquery.1.6.1.js' },
{ test: window.jQuery && window.jQuery.tmpl, nope: '/v2/mini-profiler-jquery.tmpl.beta1.js' },
{ load: '/v2/mini-profiler-includes.js?v=1.7.0.0',
complete: function() {
jQuery(function() {
MiniProfiler.init({
ids: ["025bbb91-9605-44b7-b33d-d8b196326dbc","2c74ce3e-8de6-4f8d-920a-e8708b22231b"],
path: '/v2/',
version: '1.7.0.0',
renderPosition: 'left',
showTrivial: false,
showChildrenTime: false,
maxTracesToShow: 15
});
});
}
}]);
</script>
And in my Global.asax.cs:
protected void Application_BeginRequest()
{
if (Request.IsLocal)
{
MiniProfiler.Start();
}
}
protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
EDIT: Thanks to Sam's input I've tracked the problem to my .ajaxSetup() method. When it is commented out the profile box shows again. But I can't see why this is a problem:
$.ajaxSetup({
data: "{}",
dataFilter: function (data) {
var msg;
if (data == "") {
msg = data;
}
else if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
msg = JSON.parse(data);
}
else {
msg = eval('(' + data + ')');
}
if (msg.hasOwnProperty('d')) {
return msg.d;
}
else {
return msg;
}
}
});
My guess is that the global dataFilter is interfering with MiniProfiler's $.get() for jQuery Templates template files. Calling JSON.parse() on an HTML fragment will definitely throw an error.
Since you're using a recent version of jQuery, the optimized JSON parsing isn't something you need to add manually. That functionality was included in jQuery core in 1.4.
So, most simply, try changing your global dataFilter to this:
$.ajaxSetup({
data: "{}",
dataFilter: function (msg) {
if (msg.hasOwnProperty('d')) {
return msg.d;
}
else {
return msg;
}
}
});
If that doesn't fix it, you might want to look into jQuery 1.5's converters instead of the global dataFilter, which allow you to apply a dataFilter-like operation to responses of certain Content-Type. Some good examples from the guy that actually did the jQuery 1.5 AJAX rewrite here: http://encosia.com/jquery-1-5s-ajax-rewrite-and-asp-net-services-all-is-well/#comments
This sort of makes sense, perhaps your filter is mangling the results.
Adding a conditional that bypasses the filtering if you see it is a MiniProfiler JSON result should fix it.
I am developing a mvc application.I wrote a jquery for different operations and saved in to a js file named my.js. And i included that js file into my page.
<script src="../../Scripts/my.js" type="text/javascript"></script>
How can i access ViewData from that js file. I tried many methods.But didnt worked yet.
The code i used to access ViewData from js file is shown below.
var CalanderPreference = "<%= ViewData["CalanderPreference"] %>";
But it returning an error like 'Expected ; '
Any ideas?
ViewData is not accessible on client, because it exists only on view rendering.
You could serialize your view data to json on server side, write it to hidden field, and them parse it to javascript object on client side.
You can create your javascript object on the view like in this example.
Put this into your view and not in a seperate file:
<script type="text/javascript">
$(function() {
var saleYear = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Year %>");
var saleMonth = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Month %>") - 1;
var saleDay = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Day %>");
var saleHour = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Hour %>");
var saleMinute = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Minute %>");
var saleSecond = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Second %>");
var endSaleDate = new Date(saleYear, saleMonth, saleDay, saleHour, saleMinute, saleSecond);
$("#countDownSale24").countdown({ until: endSaleDate, compact: true, format: "HMS" });
});
</script>