Stuck with Angularjs - c#

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);
}

Related

How to resolve a not working cascading drop down

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.

Not able to bind data to datatable in ASP.NET MVC

Below is my code from view from my ASP.NET MVC project. I am using datatable to create a table. I am fetching data from a Web API. Data is being returned but while binding I get the error shown here. I tried deleting a lot of code which had buttons. Now I just have code for simply binding it.
datatables warning: table id=patients - ajax error. for more information about this error, please see http://datatables.net/tn/7
jQuery code :
$(document).ready(function () {
debugger;
var table = $("#patients").DataTable({
ajax: {
url: "/api/patients",
dataSrc: ""
},
columns: [
{
data: "First_Name"
},
{
data: "phoneNumber",
render: function (data) {
debugger;
return data.toString().replace(
/(\d\d\d)(\d\d\d)(\d\d\d\d)/g, '$1-$2-$3');
}
},
{
data: "Address"
},
]
});
});
API code from controller:
public IHttpActionResult GetPatients()
{
var patientDto = getdata();
return Ok(patientDto);
}
public IEnumerable<Patient_Response> getdata()
{
IEnumerable<Patient_Response> students = null;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer 0f6af107-6ad2-4665-ad24-f09402d50082");
client.BaseAddress = new Uri("http://localhost:6600/api/");
// HTTP GET
var responseTask = client.GetAsync("patients");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<IList<Patient_Response>>();
readTask.Wait();
students = readTask.Result;
}
else //web api sent error response
{
// log response status here..
students = Enumerable.Empty<Patient_Response>();
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
}
return students;
}
What is wrong? I am not able to figure out.
Did you read the documentation: https://datatables.net/manual/tech-notes/7
This occurs when jQuery falls into its error callback handler (this callback built into DataTables), which will typically occur when the server responds with anything other than a 2xx HTTP status code.
That means that your call go the controller, failed to bring any data.
You can use the following code to see what went wrong:
$.fn.dataTable.ext.errMode = 'none';
$('#patients')
.on( 'error.dt', function ( e, settings, techNote, message ) {
alert( 'An error has been reported by DataTables: ', message );
} )
.DataTable();

Image Uploading using angular and asp.net

am trying to get the image from the PC and upload it into the DB
as like "/Images/aaa.jpg" am new to angular. Here am tried one example. Its not worked For me. i have stucked almost 3 days to solve this. but i couldn't found any tutorials for my requirement. when i debug the id, and descriptions are passing correctly, but For the path its remaining always null. and i know i need to set path to where the picture will save. but i dont know how to do that, please can anyone help me to solve this issue.
I tried this one to upload image.
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post(uploadUrl, fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(ya).error( noo );
};
There is a add button if user hit add button details want to be save. for this i used this one.
$scope.AddImage = function () {
var dataObj = {
Id: $scope.Id,
Description: $scope.Description,
Path: $scope.Path,
Location: $scope.Location,
};.
var request = $http({
method: 'POST',
url: urls.api + 'Images/AddImage',
//data: JSON.stringify(dataObj)
data: dataObj
}).success(function (data, status) {
alert('saved succesfully');
})
.error(function (error) {
$scope.status = 'Unable to load ImageDetails : ' + error.message;
console.log($scope.status);
});
}
this is my asp.net services.
public async Task<int?> Addimg (Addimg dto)
{
try
{
var d = _dbContext.img
.FirstOrDefault();
d.img_Path = dto.Path.ToString();
d.img_Description = dto.Description;
d.img_Location = dto.Location;
//mark entry as modifed
_dbContext.Entry(d).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
return d.img_Id;
}
this my asp.net controller
[HttpPost]
[Route("AddImage")]
public async Task<IHttpActionResult> AddBanner(DisplayBannersDto dto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
int? result = await _service.Addbanner(dto);
return Ok();
}
}
Please provide if there is any alternative codes.
It looks like you're uploading a file and doing nothing with it...
You could add something like the following property to your DisplayBannersDto model:
public Stream InputStream { get; set; }
You can then either save the file to disk from the stream, or in the database as a blob.

html select(dropdownlist) added one extra line angularjs

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??

getting a search bar working using AJAX in ASP.net application

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

Categories

Resources