I am creating a web app in mvc-5 with the help of angularjs i created 10-12 pages and there are lots of insert/update/delete commands there and till now everything was working fine but today when i tried to update trainer name from select(html) one extra line is being added automatically
<select ng-model="mdupdpm" ng-options="a.empname as a.empname for a in gettrainername" ng-change="zoneupd(z)" style="width:270px;"></select>
and my angularjs controller
$scope.getupdateparams = function (param) {
$('#update').modal({
show: true,
backdrop: 'static'
});
$scope.updtparam = param;
console.log($scope.data.mdupm);
$http.get('/companyregistration.asmx/updateempname', {
params: {
empname: $scope.updtparam.pm
}
}).then(function (response) {
$scope.gettrainername = response.data.info;
console.log(response.data.info);
})
}
i don't know why this is not working because i did this in my previous pages and all of that worked well I am giving one example of worked code from my previous page
<select ng-model="ucomname" ng-options="o.comname as o.comname for o in comnamelistfun" ng-change="uucomname(o)" style="width:270px;"></select>
now my controller
$scope.updatefunction = function (param) {
$scope.updateparam = param;
//comnamebyid
$scope.updmodal = true;
$http.get('/csuv.asmx/getcompanyname', {
params: {
log: log,
pm: pm,
id: $scope.updateparam.Id
}
})
.then(function (response) {
{
$scope.updmodal = false;
$scope.comnamelistfun = response.data.cdetails;
}
$scope.ucomname = $scope.comnamelistfun[0].comname;
});
what is wrong guys??
Related
I have a cascading dropdown like for eg first dropdown shows the list of countries and based on the selection of countries the next dropdown gets populated. The problem is that in development environment it's working fine but when deployed in a server the first dropdown gets populated correctly as it's elements come from resource file and after selection of first drop down I get an error.
JS :
<script>
$(document).ready(function () {
$("#Site").change(function () {
var SelectedVal = $(this).val();
$("#Model").html('');
$("#Model").append($("<option></option>").attr("value", '')
.text(' '));
if (SelectedVal != '') {
$.get("/Home/GetModelList", { Sid: $("#Site").val() }, function (data) {
$("#Model").empty();
$("#Model").html('');
$("#Model").append($("<option></option>").attr("value", '')
.text(' '));
if (data.modelAlert != null) {
alert(data.projectAlert);
}
$.each(data.models, function (index, item) {
$("#Model").append($('<option></option>').text(item));
});
});
}
})
});
</script>
Controller :
public JsonResult GetModelList()
{
List<string> models = db.GetModels();
string modelAlert = alert.GetAlert();
var result = new { modelAlert, models };
return Json(result, JsonRequestBehavior.AllowGet);
}
The error message that I get is
Failed to load resource: the server responded with a status of 404 (Not Found) Home/GetModelList?Sid=Ind:1
I checked for similar problems like this and it was all about the JS path or the controller path but I've already given the absolute path. Can someone let me know where am I going wrong, let me know if any additional data is needed.
Thanks
$.get("/Home/GetModelList", { Sid: $("#Site").val() }, function (data) {
The above line was causing the routing problem, usually when we call a controller action from js in this way there tends to be a routing problem due to the folder structure reference. In order to avoid this routing problem and to be more clear we can also call controller action from js like below
$.get('#Url.Action("MethodName", "ControllerName")', function (data) {
This resolved my issue.
im trying to get a sech bar going for searching though a table and only displaying the results based off the title . the program does give me any errors or exceptions but when i press the search button nothing happens.
any help would be appreciated
the code inside my view
<script>
$(document).ready(function () {
getFileSharingsAjax(0)
});
function searchFileSharings() {
var searchQuery = $("#txtSearch").val();
getFileSharingsAjax(searchQuery);
}
function filterMovies() {
$("#txtSearch").val("");
getFileSharingsAjax("");
}
function getFileSharingsAjax(searchQuery) {
$.ajax({
type: "GET",
url:"#Url.Action("GetFileSharingsAjax")",
data: {
searchQuery: searchQuery
}, success:function(ViewResult){
$("#ajax-files").html(ViewResult);
}
});
}
</script>
my controller class
public ActionResult GetFileSharingsAjax(string searchQuery)
{
var query = from m in db.FileShare
select m;
if (!string.IsNullOrEmpty(searchQuery))
{
query = query.Where(s => s.Title.Contains(searchQuery));
}
return View("Files", query.ToList());
}
any help would be appreciated
I am learning AngularJS and how to use it with ASP.NET Web API, and I am struggling right now with displaying the returned refreshed list of products after deleting one product by the manager. When he deletes a product successfully, the list of products will be updated immediately after that deletion.
The deletion function works well, but after doing the deletion, I got the following error message:
I tried to follow the answer mentioned in this question HERE, but it seems that the developer returns a status from the deletion function in the Web API which is totally different than my case.
Here's the code of ProductRepository class:
public List<T_Product> GetAllProducts()
{
var query = from product in db.T_Product
select product ;
return query.ToList();
}
public List<T_Product> DeleteProduct(int productId)
{
var pro = (from product in db.T_Product
where product .ProductId == productId
select product ).SingleOrDefault();
db.T_Product.DeleteObject(pro);
db.SaveChanges();
return GetAllProducts();
}
Here's the code of deletion function in Web API:
public HttpResponseMessage Delete(int id)
{
var products = productRepository.DeleteProduct(id);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
return response;
}
And here the AngularJS Controller Code:
app.controller('productsController', [productsFactory', 'productFactory', function (productsFactory, productFactory) {
var vm = this;
vm.Products = productsFactory.query();
// callback for ng-click 'deleteProduct':
vm.deleteProduct = function (aId) {
productFactory.delete({ id: aId });
vm.Products = productsFactory.query();
};
}]);
And here's the AngularJS Service Code:
app.factory('productsFactory', function ($resource) {
return $resource('/api/products', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
});
app.factory('productFactory', function ($resource) {
return $resource('/api/products/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: { id: '#id' } },
delete: { method: 'DELETE', params: { id: '#id' } }
})
});
I debugged and captured the network packet using F12 in the IE 9 and the code returns the updated list but it did not show in the page. Why?
So how can I display the returned updated list of products immediately after any successful deletion operation?
As far as I can tell, the problem is exactly the same as the question you linked. productFactory.delete({ id: aId }); is an asynchronous call, so it needs time to send data to the server and get data back. You should put the code you want to happen after the delete occurs inside the delete's callback function:
// callback for ng-click 'deleteProduct':
vm.deleteProduct = function (aId) {
productFactory.delete({ id: aId }, function() {
vm.Products = productsFactory.query();
});
};
This way you can be sure the query function will happen after the item is deleted on the server.
Ideally you shouldn't need to call .query() again, and would just delete the item locally. That way you wouldn't need to wait for another server request/response.
I think you should be setting the value of vm.Products in a callback - Angular is resolving the asynchronous value initially (so simply assigning productsFactory.query directly to the vm.Products does work when the controller is created, as all async operations are completed before rendering), but when it comes to refreshing it after delete that doesn't work - translating your code so it is all callback-happy:
app.controller('productsController', [productsFactory', 'productFactory', function (productsFactory, productFactory) {
var vm = this;
productsFactory.query(function (products) {
vm.Products = products;
});
// callback for ng-click 'deleteProduct':
vm.deleteProduct = function (aId) {
productFactory.delete({ id: aId }, function() {
productsFactory.query(function (products) {
vm.Products = products;
});
});
};
}]);
Setting the resource to accept an array response
delete: { method: 'DELETE', params: { id: '#id' }, isArray: true }
and either using the value from the callback
vm.deleteProduct = function (aId) {
productFactory.delete({ id: aId }, function(remainingProducts) {
vm.Products = remainingProducts;
});
};
or the promise from the resource method
vm.deleteProduct = function (aId) {
vm.Products = productFactory.delete({ id: aId });
};
should do the trick.
As others have mentioned, you would typically just delete the item locally once the delete call returns (that is, inside the callback). What I tend to do is removing the item instantly and then re-add it if something goes wrong (by providing a second error-callback). Keep in mind though that the list might have changed in the meantine (unless the UI is somehow 'locked' during the AJAX call).
As a side note: the productFactory is also concerned with products, so you might want to consider merging the two resources. Having an empty or no id will go to just the right server resource.
When I make ajax request to the server with breakpoint in the action method it stops on this breakpoint only the first time. After clicking for second, third etc. it goes but never stops on this breakpoint. When I change the method from GET to POST it stops every time. What is the reason for this behaviour ?
CLIENT SIDE:
$(function () {
setListAction();
});
function setListAction() {
$("li.list").on("click", function () {
alert("active");
var id = $(this).attr("file-id");
$.ajax({
type: "GET",
url: "TechAcc/ManageFile/" + id,
beforeSend: function myfunction() {
$("#loading").css("display", "block");
$("#fade").css("display", "block");
},
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
});
});
}
SERVER SIDE:
[HttpGet]
public ActionResult ManageFile(int id = 0)
{
FileModel model = null;
if (id != 0)
model = new FileModel() { File = _repository.GetFileBy(id), GetAllFiles = _repository.GetAllFiles() };
else if (Session["Model"] != null)
model = (FileModel)Session["Model"];
else
model = new FileModel() { GetAllFiles = _repository.GetAllFiles() };
return View(model);
}
if your div with id "content" has list, it will not work.
<div id="content">
if your list is here, it won't work.
...
<li class="list">...</li>
...
</div>
if your design is like that, you need to bind click event after you replace your HTML response. i.e.,
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
//adding code here.
$("div#content").find("li.list").on("click", function() {
//same above click code should come here.
//Note: this newly added code block should not come here in click.
});
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
Hello i'm new to angularjs and i'm creating an Angularjs application with visualstudio 2012 mvc4 and i need some help with a request.
this is my get method
// GET: /getCard/
Logic l = new Logic();
public List<Cards> Index()
{
var cards = ml.getSortedDeck();
return cards;
}
here is my js code
MemoryApp.factory('Cards', function($resource){
return $resource('/getCard/', { method: 'GET', isArray: true });
});
var ColourCtrl = function ($scope, Cards, $routeParams, $resource) {
$scope.cards = [];
$scope.setcards = function () {
Cards.query(function (data) {
console.log(data);
$scope.cards = $scope.cards.concat(data);
});
}
$scope.setcards();
}
when i stepped through my backend code it worked fine, i got 16 hits back in the "cards" list which is the right amount. Though when i check my console.log on the website i have an array with 59 items that are unuseable to me.
When i check the response section in under the network tab i get this message
"System.Collections.Generic.List`1[Memory.Models.Cards]" and that seems right to me.
best regards /M
Return JSON.
public JsonResult Index()
{
var cards = ml.getSortedDeck();
return Json(cards, JsonRequestBehavior.AllowGet);
}