I am having a strange problem. I am using AngularJS in my project. I have some partial views where I am having different implementations of AngularJS functionality. I am loading all my partial views via Ajax call. Ajax call does load partial view in container but its AngularJS functionality does not work. I have noticed that when I give reference to AngularJS via CDN then it works but when I copy and paste CDN JS into my local js file then it does not.
Please suggest what is the issue.
Here is the code:
Partial View:
<div ng-controller="EmployeeController">
<div>
ID: <input type="text" id="txtID" ng-model="employeeID" /><br />
Name: <input id="txtName" type="text" ng-model="employeeName" />
<button id="btnAddEmployee" ng-click="addEmployee()">Add Employee</button>
<button id="btnRemoveEmployee" ng-click="removeEmployee()">Remove Employee</button>
<ul >
<li ng-repeat="employee in employees">
Employee id is: {{employee.id}}<br />
Employee name is: {{employee.name}}
</li>
</ul>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script>
var employees = [{ name: 'ABC', id: '1' },
{ name: 'XYZ', id: '2' },
{ name: 'KKK', id: '3' }];
function EmployeeController($scope) {
$scope.employees = employees;
$scope.addEmployee = function () {
$scope.employees.push({ name: $scope.employeeName, id: $scope.employeeID });
}
$scope.removeEmployee = function () {
$scope.employees.pop();
}
}
</script>
Controller:
public PartialViewResult LoadViews(int id)
{
if (id == 1)
return PartialView("TestView1Partial");
else
return PartialView("TestView2Partial");
}
Main View:
<ul>
<li>
View 2
</li>
</ul>
<div id="dvContainer">
<script>
function LoadView2() {
$.ajax({
url: "/home/LoadViews?id=2",
type: "GET",
datatype: "html",
async:true,
success: function (result) {
$("#dvContainer").html(result);
}
});
}
</script>
Thanks,
JSHunjan
In your Ajax call change the async:false and it might work.
Related
I am working with ASP.NET MVC .
I give the proper url name but error is the resource is not found.
I am click the checkout button and trying to open view but view is not open.
Please see below code.
cartDisplay.cshtml
#{
ViewBag.Title = "cartDisplay";
}
<h2>Add to Cart Details</h2>
<script src="~/kendo/js/kendo.all.min.js"></script>
<div style="display: inline">
<div class="text-left">
<button class='btn btn-group-sm btn-success' onclick='submit()'>CheckOut</button>
</div>
</div>
<div id="example">
<br />
<br />
<div id="grid"></div>
<script>
$(document).ready(function () {
//here other code
function submit() {
debugger
$.ajax({
url: "/User/addToCartOrderStore", //here I am giving the proper url but error is resource not found error
type: 'GET',
cache: false,
contentType: false,
processData: false,
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
}
</script>
UserController.cs
//Shipping Details and order details
[HttpGet]
public ActionResult addToCartOrderStore()
{
return View();
}
[HttpPost]
public ActionResult addToCartOrderStore(FormCollection sh)
{
....
}
I am trying to open below view but below view is not open
addToCartOrderStore.cshtml:
#{
ViewBag.Title = "addToCartOrderStore";
}
<h2>AddToCart OrderStore</h2>
<script src="~/kendo/js/kendo.all.min.js"></script>
<br />
<div class="navbar navbar-inverse text-center">
<div class="container text-center">
<div class="navbar-collapse collapse text-center">
<ul class="nav navbar-nav text-center">
#*<li>#Html.ActionLink("Home", "index")</li>
<li> #Html.ActionLink("My Cart", "cartdisplay")</li>
<li> #Html.ActionLink("My Orders", "orderdisplay")</li>*#
<li>#Html.ActionLink("Logout", "Logout")</li>
</ul>
</div>
</div>
</div>
<form id="form"></form>
<script>
$(document).ready(function () {
var today = new Date();
var maxDate = today.setDate(today.getDate() + 60);
$("#form").kendoForm({
layout: "grid",
grid: {
cols: 2,
gutter: 20
},
items: [
{
type: "group",
label: "Customer Address",
items: [
{
field: "firstname",
label: "First Name:",
validation: { required: true }
},
{
field: "lastname",
label: "Last Name:",
validation: { required: true }
},
See below error image:
I am trying to open view but give an error the resource cannot be found.
I trying to return view but give an error but view is not shown.
need help
I currently have a partial view that renders at the top of every page on the site. The point of this partial view is to provide a form that lets the user do a quick search. I have set the partial view form up as follows:
#using (Html.BeginForm())
{
<div class="col-md-7" style="text-align: right">
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.TextBox("caseReference")
<button type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
}
#Html.Partial("_MainNavigation")
</div>
</div>
</nav>
<script type="text/javascript">
$(function () {
$("form").on("submit", function (event) {
event.preventDefault();
var request = { caseReference: $('#caseReference').val() };
submitForm(request, '#Url.Action("CaseSearch", "QuickSearch", new { area = "Search" })');
});
});
</script>
However under the page source the form action renders as a request to the home page with a post action. I have read numerous examples and this task seems very straight forward. Would it be a better idea to use the parameters on the #html.BeginForm() method?
So after spending a few hours researching, I have finally got the quick search functionality to work on the home page of my site. In the razorview I have the following code:
<div class="input-group input-group-sm col-sm-6 pull-right">
#Html.Kendo().MaskedTextBox().Name("name").Mask("000000/0000").Deferred()
<button id="search" type="submit">
<i class="fa fa-search"></i>
</button>
<script type="text/javascript">
$(function () {
$("#search").on("click", function (event) {
event.preventDefault();
var value = $('#name').val();
value = value.replace(/[/]/g, "_");
var refVal = value;
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
$.ajax({
type: 'GET',
url: url,
cache: false,
dataType: 'json',
contentType: "application/json;",
success: function (result) {
if (result.success) {
window.location.href = result.url;
}
else {
bootbox.alert(result.message);
}
}
});
});
});
However in regards to the following line:
var url = '#Url.Action("Action", "Contoller", new { area = "Area" })' + '//' + refVal;
If I hard code the url and append the search term it works on the Home page because we are at the root directory but from other pages it fails, To get around this I tried to use #Url.Action. However this is producing the following result in the html soure code:
var url = '' + '//' + refVal;
Is there a certain way to use the URL.Action method from withing JS?
I have been continously trying to implement routing in Angularjs with Mvc 4.0 project but I am not able to do it.
I have created a empty MVC 4.0 project and added a controller "HomeController". Then I added a folder in Views with name Home having three views. One is index which opens when we run application as in route config we have route for homecontroller and Index Action.So, basically assuming the index page as the main page in Singlepage application, I have defined some code in the index page as given in 6oish book enter link description here.
Index. CShtml
#{
ViewBag.Title = "Index";
}
<style>
.container {
float: left;
width: 100%;
}
</style>
<script src="~/Scripts/angular.min.js"></script>
<h2>Practising Angular</h2>
List
Edit
<div ng-app="demoApp">
<div class="container">
<div ng-view=""></div>
</div>
</div>
<script>
var demoApp = angular.module('demoApp', []);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', { controller: 'SimpleController', templateUrl: 'Home/List' })
.when('/Edit', { controller: 'SimpleController', templateUrl: 'Home/Edit' })
.otherwise({ redirectTo: '/' });
});
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [{ name: 'Dave jones', city: 'Phoenix' },
{ name: 'Jhon Dena', city: 'Mexico' },
{ name: 'Bradshaw', city: 'WashingTon' },
{ name: 'Rey Mysterio', city: 'Brazil' },
{ name: 'Randy', city: 'California' }, ];
});
$scope.addCustomer = function () {
$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city })
};
</script>
Now, I need two more Views which are defined in the above route and they are as follows:
List.cshtml
#{
ViewBag.Title = "List";
}
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="filter.name" />
<ul>
<li ng-repeat="objCust in customers | filter:filter.name">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
Customer Name:<br />
<input type="text" ng-model="newCustomer.name" /><br />
Customer city:<br />
<input type="text" ng-model="newCustomer.city" /><br />
<button ng-click="addcustomer()">Add customer</button>
</div>
and Last one is
Edit.cshtml
#{
ViewBag.Title = "Edit";
}
<h2>Edit the particular user. Things are under construction</h2>
<h2>Listing the users in order </h2>
<div class="container">
Name: <input type="text" ng-model="city" />
<ul>
<li ng-repeat="objCust in customers | filter:city">{{objCust.name }}-{{objCust.city}}
</li>
</ul>
</div>
Here is the home controller
namespace Routing_Angular.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult List()
{
return PartialView();
}
public ActionResult Edit()
{
return PartialView();
}
}
}
I am attaching a image to show the Project structure.
I ma running the application, I can see the empty page where it is written "Practising Angular" with two anchor tags "List" and "Edit". I am not getting any change on changing the url.I added "/" in the url and It is not changed . then I added a "/Edit". then also I found no change. I have added anchor tags at the top in index page then also there is no change. only url gets changed. Please guide me where I am doing wrong.
There are a few things you need to fix in your views and angular code.
First of all, when defining the SimpleController, you have defined the addCustomer function outside the controller.
You should have the following controller definition:
demoApp.controller('SimpleController', function ($scope) {
$scope.customers = [{ name: 'Dave jones', city: 'Phoenix' },
{ name: 'Jhon Dena', city: 'Mexico' },
{ name: 'Bradshaw', city: 'WashingTon' },
{ name: 'Rey Mysterio', city: 'Brazil' },
{ name: 'Randy', city: 'California' }, ];
$scope.addCustomer = function () {
$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });
};
});
Then in your list view, the function declared for the "Add Customer" button is wrong, as it is case sensitive. You should have addCustomer instead of addcustomer (with capital C, as defined in your SimpleController):
<button ng-click="addCustomer()">Add customer</button>
Also, I am not sure which version of angular you are using, but from version 1.2.0, routing needs to be loaded as a separate module (see this error). You can install it following these instructions, adding the script angular-route.min.js and declaring your module as:
var demoApp = angular.module('demoApp', ['ngRoute']);
You will know that you need to load the routing module because you will see an exception in the browser console when the initial Index view loads. (It's always a good idea to check the browser console for JS errors anyway)
That should be everything, hope it helps!
I have a form like this and i need to submit all values in this
form except those with class="noDisplay". Pass it to the
controller and update the value to "pd-price". Everything works fine, just that i cannot find a way to ignore the noDisplay values to submit the form.
<div class="cart">
<strong>
<span class="pd-price">80.407.000đ</span>
</strong>
</div>
<form method="post" id="product-details-form" action="xxx">
<ul>
<li class="showImg-target noDisplay">
<input type="radio" name="product_attribute_46_3_113"> [+3.870.000]
</li>
<li class="showImgtarget">
<input type="radio" name="product_attribute_46_4_113">[+1.000.000]</li>
<li class="showImgtarget noDisplay">
<input type="radio" name="product_attribute_46_5_113">[-1.500.000]</li>
<li class="showImgtarget noDisplay">
<input type="radio" name="product_attribute_46_6_113"></li>
..... a lot more
</ul>
</form>
<script type="text/javascript">
$(function () {
updateStatus();
$('*[name^=product_attribute]').change(function () {
updateStatus();
});
function updateStatus() {
$.ajax({
cache: false,
url: '/Catalog/UpdateProductStatus',
data: $('#product-details-form').serialize(),
type: 'post',
success: function (data) {
$('.summary-info').html(data.View);
$('.pd-price').html(data.Price);
$('.powered-icon').replaceWith(data.Pictures);
}
});
}
});
</script>
You can use :not() selector:
$('#product-details-form li:not(.noDisplay) :input').serialize();
I'm trying to run up a little prototype in Ember.JS at the moment with a view to completely re-writing the UI of a web application as an Ember Application running against a WebAPI, but although I've managed to get Ember running OK, I cannot get jqueryui to initialise the tabs correctly.
It seems to work fine if within the view I put static data for tabs to be created from, but if I'm using dynamic data then it just doesn't work.
I have an Ember view template
<script type="text/x-handlebars" id="index">
<div id="tabs" class="ui-tabs">
<ul>
{{#each model}}
<li>
<span class="ui-icon ui-icon-person"></span>
<a {{bindAttr href="route"}} {{bindAttr title="tabTitle"}}><span>{{title}}</span></a>
</li>
{{/each}}
</ul>
{{#each model}}
<div {{bindAttr id="tabTitle"}}>
<p>
Retrieving Data - {{title}}
</p>
</div>
{{/each}}
</div>
</script>
and a view
App.IndexView = Ember.View.extend({
templateName: 'index',
didInsertElement: function () {
var tabs = $("#tabs").tabs();
}
});
and a model
App.Section = DS.Model.extend({
name: DS.attr('string'),
title: DS.attr('string'),
tabTitle: function () {
return 'tab-' + this.get('name');
}.property("name"),
route: function () {
return '#' + this.get('tabTitle');
}.property("tabTitle")
});
App.Section.FIXTURES = [
{
id: 1,
name: 'home',
title: 'Home'
},
{
id: 2,
name: 'users',
title: 'Users'
}
];
It appears to generate the HTML correctly (from checking in Firebug), but this does not work, where as if I replace the template with
<script type="text/x-handlebars" id="index">
<div id="tabs" class="ui-tabs">
<ul>
<li>
<span class="ui-icon ui-icon-person"></span>
<span>Home</span>
</li>
<li>
<span class="ui-icon ui-icon-person"></span>
<span>Users</span>
</li>
</ul>
<div id="tab-home">
<p>
Retrieving Data - Home
</p>
</div>
<div id="tab-users">
<p>
Retrieving Data - Users
</p>
</div>
</div>
</script>
it works perfectly.
I'm assuming that it's something to do with the DOM not being completely rendered by the time the tabs are initialised, but everything I can find says that didInsertElement is the place to do it, and I have had time to dig deeper yet.
I'd be grateful for any ideas.
Edit: I've managed to make this work in a fashion by doing the following:
App.IndexView = Ember.View.extend({
templateName: 'index',
didInsertElement: function () {
Ember.run.next(this, function () {
if (this.$('#tab-users').length > 0) {
var tabs = $('#tabs').tabs();
} else {
Ember.run.next(this.didInsertElement);
}
});
},
});
The problem with this is that 1) it requires me to know what one of the last elements that will be written to the view is called (and obviously with dynamic data I won't necessarily know that), so that I can keep checking for it, and 2) the inefficiency of this technique makes me want to scream!
In addition, we get a good old FoUC (Flash of Unstyled Content) after things have been rendered, but before we then get JQueryUI to style them correctly.
Any suggestions gratefully received.
It's still not nice... but this at least does work, and is reasonably efficient...
From Ember.js - Using a Handlebars helper to detect that a subview has rendered I discovered how to write a trigger, and because of the way that the run loop seems to work, inserting the trigger in the last loop on the page causes it to be called n times, but only after the loop is complete, so a quick state check "hasBeenTriggered" ensures that you only execute the delgate function once.
My code now looks like this:
<script type="text/x-handlebars" id="index">
<div id="tabs" class="ui-tabs">
<ul>
{{#each model}}
<li>
<span class="ui-icon ui-icon-person"></span>
<a {{bindAttr href="route"}} {{bindAttr title="tabTitle"}}><span>{{title}}</span></a>
</li>
{{/each}}
</ul>
{{#each model}}
<div {{bindAttr id="tabTitle"}}>
<p>
Retrieving Data - {{title}}
</p>
</div>
{{trigger "triggered"}}
{{/each}}
</div>
</script>
with the trigger
Ember.Handlebars.registerHelper('trigger', function (evtName, options) {
options = arguments[arguments.length - 1];
var hash = options.hash,
view = options.data.view,
target;
view = view.get('concreteView');
if (hash.target) {
target = Ember.Handlebars.get(this, hash.target, options);
} else {
target = view;
}
Ember.run.next(function () {
target.trigger(evtName);
});
});
and view
App.IndexView = Ember.View.extend({
templateName: 'index',
hasBeenTriggered: false,
triggered: function () {
if (!this.get("hasBeenTriggered")) {
var tabs = $('#tabs').tabs();
this.set("hasBeenTriggered", true);
}
}
});
I'd love to know if there's a better way of doing this, as this still doesn't get round the FOUC problem either (which again can be done with more JS hacks)... :(