My angular method does not fire - javascript

It's the first time that I'm using angular and I am a newbie in this field; the methods do not fire at all and the changes in style do not happen. I checked everything several times but I cannot find my mistake. Help me please. Thanks in advance.
Here is the angular code:
<script language="javascript">
function CustomerPresenter($scope, $http) {
$scope.Customer = {
"CustomerName": "",
"CustomerCode": "",
"CustomerAmount": "",
"CustomerAmountColor": ""
};
alert($scope.Customer);
$scope.Customers = {};
alert($scope.Customers)
$scope.$watch("Customers", function () {
for (var i = 0; i < $scope.Customers.length; i++) {
alert(i);
var cust = $scope.Customers[i];
cust.CustomerAmountColor = $scope.getColor(cust.CustomerAmount);
}
});
$scope.getColor = function (Amount) {
if (Amount == 0) {
return "";
}
else if (Amount > 100) {
return "Blue";
}
else {
return "Red";
}
alert(Amount);
}
$scope.$watch("Customer.CustomerAmount", function () {
$scope.Customer.CustomerAmountColor = $scope.
getColor($scope.Customer.CustomerAmount);
alert(getColor);
});
$scope.Add = function () {
$http({ method: "POST", data: $scope.Customer, url: "Submit" }).
success(function (data, status, headers, config) {
$scope.Customers = data;
alert(data);
$scope.Customer = {
"CustomerName": "",
"CustomerCode": "",
"CustomerAmount": "",
"CustomerAmountColor": ""
};
});
}
$scope.Load = function () {
$http({ method: "GET", url: "GetCustomerJSON" }).
success(function (data, status, headers, config) {
$scope.Customers = data;
alert($scope.Customers);
});
}
$scope.Load();
}
var app = angular.module("myApp", []);
app.controller('CustomerPresenter', CustomerPresenter);
</script>
and this is my Html:
<body ng-app="myApp">
<div>
<div ng-controller="CustomerPresenter">
<form id="frm">
<i> Customer Name :</i> <input name="customer.CustomerName" ng-model="Customer.CustomerName" id="txtCustomerName" type="text" />
<br />
#Html.ValidationMessageFor(z => z.customer.CustomerName)
<br />
<i> Customer Code :</i><input name="customer.CustomerCode" ng-model="Customer.CustomerCode" id="txtCustomerCode" type="text" />
<br />
<br />
#Html.ValidationMessageFor(z => z.customer.CustomerCode)
<br />
<i>Customer Amount :</i><input name="customer.CustomerAmount" style="background-color:{{ Customer.CustomerAmountColor }}" ng-model="Customer.CustomerAmount" id="txtCustomerAmount" type="text" />
</form>
<br />
<br />
<input id="btn" type="button" value="add customer" ng-click="Add()" />
<br />
<div id="status" style="width:200px;height:20px"></div>
<table id="tblCustomer">
<tr>
<td>Customer Name</td>
<td>Customer Code</td>
<td>Customer Amount</td>
</tr>
<tr ng-repeat="cust in Customers">
<td>{{cust.CustomerName}}</td>
<td>{{cust.CustomerCode}}</td>
<td style="background-color: {{ cust.CustomerAmountColor }}">{{cust.CustomerAmount}}</td>
</tr>
</table>
</div>
</div>
and the methods in controller are:
public ActionResult Submit(Customer customerObj)
{
if (ModelState.IsValid)
{
DataAccessLayer dal1 = new DataAccessLayer();
dal1.customers.Add(customerObj);
dal1.SaveChanges();
}
DataAccessLayer dal = new DataAccessLayer();
List<Customer> custColl = dal.customers.ToList<Customer>();
return Json(custColl, JsonRequestBehavior.AllowGet);
}
public ActionResult GetCustomerJSON()
{
DataAccessLayer dal = new DataAccessLayer();
List<Customer> lstCustomers = dal.customers.ToList<Customer>();
return Json(lstCustomers, JsonRequestBehavior.AllowGet);
}

Related

Get the HTML table Checked item Id's to list and Pass to Controller

In my ASP.NET MVC project, there is a table that shows the user view the information of file type and Id (Hidden).
Whenever the user put checked the checkboxes and clicks on the Send Request Mail Button, I want to get the IDs of the checked rows and pass them to the controller as a List of Ids.
This is the table view
<tbody>
#foreach (var item in Model.ReqDocumentsViewModel.OrderByDescending(x => x.Id))
{ <tr class="even pointer">
<td style="display:none;">#item.Id</td>
<td>#item.FileType</td>
<td>#item.Note</td> #if (item.RequestStatus == false) { <td> Not Requested; </td> } else { <td> Requested; </td> } <td>
<input type="checkbox" value="#item.Id" id="chk" />
</td>
<td>
<button type="button" onclick="RemoveReqDocument()" class="btn btn-danger">Remove</button>
</td>
</tr>
}
</tbody>
<button type="button" class="btn btn-primary sm" onclick="SendMailNotification();">Send Request Mail</button>
This is what I tried.
function SendMailNotification() {
const selectedRows = [...$('table tbody tr:has("input:checked")')]
.map(tr => [...$(tr).find('td:lt(1)')]
.reduce((res, td) => (res[$(td).attr('prop')] = $(td).text(), res), {}))
console.log(selectedRows)
var newOrders = $.map(selectedRows, function (element) {
var obj = {};
for (var key in element) {
obj.Id = key;
}
return obj;
});
$.ajax({
type: "POST",
url: "/Task/RequestDocument",
data: JSON.stringify(newOrders),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
if (r == false) {
alert("You have to enter Order Qty first");
} else {
alert("Order Created");
location.reload();
}
}
});
}
In Controller
public JsonResult RequestDocument(List < ReqDocList > idQs)
{
}
Model
public class ReqDocList
{
public int Id { get; set; }
}
I want to get the IDs of the checked rows and pass them to the
controller as a List of Ids.
Below is a work demo, you can refer to it.
ReqDocListVM:
public class ReqDocListVM
{
public ICollection<ReqDocList> ReqDocList { get; set; }
}
TaskController:
public class TaskController : Controller
{
public static List<ReqDocList> ReqDocList = new List<ReqDocList>()
{
new ReqDocList() {Id =1},
new ReqDocList() {Id =2},
new ReqDocList() {Id =3},
new ReqDocList() {Id =4}
};
public IActionResult Index()
{
var model =new ReqDocListVM();
model.ReqDocList= ReqDocList;
return View(model);
}
public JsonResult RequestDocument(List<int> ids)
{
return Json(ids);
}
}
Index view:
#model ReqDocListVM
<table class="table table-bordered table-light">
<tbody>
#foreach (var item in Model.ReqDocList)
{
<tr class="even-pointer" chk-id="#item.Id">
<td>
<input type="checkbox" value="#item.Id" id="chk" />
</td>
<td>
<button type="button" onclick="RemoveReqDocument()" class="btn btn-danger">Remove</button>
</td>
</tr>
}
</tbody>
</table>
<button id="bt"type="button" class="btn btn-primary sm" >Send Request Mail</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var Ids = [];
$(".even-pointer").click(function () {
$(this).toggleClass("selected");
var Id = $(this).attr('chk-id');
if ($(this).hasClass("selected")) {
Ids.push(Id);
}
else {
Ids = Ids.filter(function (id) {
return id !== Id;
});
}
});
$("#bt").click(function () {
console.log(Ids);
$.ajax({
type: "POST",
url: "/Task/RequestDocument",
data: { "ids": Ids },
success: function (response) {
alert(response);
}
});
});
});
</script>
result:

How can i add/send multiple records in asp.net MVC using jQuery?

I want to send multiple records in the database using javascript in asp.net mvc i tried many different ways but all in vain. here I have the best code which can send the data to the controller but the file is not sending.
I search different ways i have found one is with FormData but i am unable to handle that in this context.
Controller:
public ActionResult SaveAllFeedback(FEEDBACKVM[] fEEDBACKs)
{
try
{
if (fEEDBACKs != null)
{
FEEDBACK fEEDBACK = new FEEDBACK();
foreach (var item in fEEDBACKs)
{
fEEDBACK.DATE = item.DATE;
fEEDBACK.COMMENT = item.COMMENT;
fEEDBACK.STUDENTID = item.STUDENTID;
fEEDBACK.TEACHERID = db.TEACHERs.Where(x => x.EMAIL == User.Identity.Name).FirstOrDefault().ID;
if (item.HOMEWORK != null)
{
fEEDBACK.HOMEWORK = SaveToPhysicalLocation(item.HOMEWORK);
}
db.FEEDBACKs.Add(fEEDBACK);
}
db.SaveChanges();
return Json("Done", JsonRequestBehavior.AllowGet);
}
return Json("Unable to save your feedback! Please Provice correct information", JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json("Unable to save your feedback! Please try again later.", JsonRequestBehavior.AllowGet);
}
}
ViewPage:
<form>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<input name="DATE" id="DATE" type="date" class="form-control" />
</div>
<table class="table table-responsive table-hover" id="table1">
<thead>
<tr class="bg-cyan">
<th></th>
<th>RollNumber</th>
<th>Comment</th>
<th>Homework</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.students)
{
<tr>
<td>
<input name="STUDENTID" type="text" value="#item.Key" hidden="hidden" />
</td>
<td>
<input name="STUDENTROLLNUMBER" type="text" value="#item.Value" class="form-control" readonly="readonly" />
</td>
<td>
<input name="COMMENT" type="text" class="form-control" />
</td>
<td>
<input name="HOMEWORK" type="file" class="form-control" />
</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-10">
#Html.ValidationMessage("ErrorInfo", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="saveButton" type="submit" class="btn btn-danger">Save Attendance</button>
</div>
</div>
</form>
Script:
<script>
//After Click Save Button Pass All Data View To Controller For Save Database
function saveButton(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SaveAllFeedback", "Teacherss")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveButton").click(function (e) {
e.preventDefault();
var formData = new FormData();
var arr = [];
arr.length = 0;
$.each($("#table1 tbody tr"), function () {
//arr.push({
// //DATE: $("#DATE").val(),
// //STUDENTID: $(this).find('td:eq(0) input').val(),
// //COMMENT: $(this).find('td:eq(2) input').val(),
// //HOMEWORK: $(this).find('td:eq(3) input').val()
// });
formData.append("DATE", $("#DATE").val());
formData.append("STUDENTID", $(this).find('td:eq(0) input').val());
formData.append("COMMENT", $(this).find('td:eq(2) input').val());
formData.append("HOMEWORK", $(this).find('td:eq(3) input')[0].files[0]);
});
var data = JSON.stringify({
fEEDBACKs: formData
});
$.when(saveButton (data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
I just want to send multiple records with the file to the database
are you sure you want send the files???? if yes then
Your form tag should be look like this
<form id="yourid" action="youraction" enctype="multipart/form-data">
Form Component
</form>
NOTE:- enctype="multipart/form-data" tag is important
and then controller should be look like this
public ActionResult YourController(FormCollection data)
{
if (Request.Files.Count > 0)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//you can save the file like this
string path = Server.MapPath("~/Yourpath/FileName" + fileName.Substring(fileName.LastIndexOf('.')));
file.SaveAs(path);
//or you can load it to memory like this
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
//use it how you like
}
}
return View();
}

405 (Method Not Allowed) in Angular JS With WCF Service

Currently I am working on WCF project. I am consuming my wcf project into Angular JS Application but when I run the application it does not provide any error. There are errors when I launch developer tools in Google Chrome and I cannot insert, update and delete etc. It's showing following errors...... Anyone help me to correct this errors I would be grateful.
?o=3&g=EC0825C4-90A4-2692-D257-CD2C2B565912&s=1A2C77E8-0498-4A11-B8B8-D740DBEC71C4&z=1403834305:2 Uncaught SyntaxError: Unexpected token <
2angular.js:12701 OPTIONS http://localhost:50028/StudentService.svc/AddNewStudent 405 (Method Not Allowed)
Index:1 XMLHttpRequest cannot load http://localhost:50028/StudentService.svc/AddNewStudent. Response for preflight has invalid HTTP status code 405
Modules.js:52 Some error Occured[object Object]
Index:1 GET http://localhost:50028/StudentService.svc/GetAllStudent/ 400 (Bad Request)
angular.js:14642 ReferenceError: $log is not defined
at Modules.js:18
at angular.js:17000
at m.$digest (angular.js:18182)
at m.$apply (angular.js:18480)
at l (angular.js:12501)
at XMLHttpRequest.s.onload (angular.js:12655) "Possibly unhandled rejection: {}"
Her is code in Angular JS ...
/// <reference path="../angular.min.js" />
var app;
(function () {
app = angular.module("RESTClientModule", []);
app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService) {
$scope.OperType = 1;
//1 Mean New Entry
GetAllRecords();
//To Get All Records
function GetAllRecords() {
var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
promiseGet.then(function (pl) { $scope.Students = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.StudentID = "";
$scope.Name = "";
$scope.Email = "";
$scope.Class = "";
$scope.EnrollYear = "";
$scope.City = "";
$scope.Country = "";
}
//To Create new record and Edit an existing Record.
$scope.save = function () {
var Student = {
Name: $scope.Name,
Email: $scope.Email,
Class: $scope.Class,
EnrollYear: $scope.EnrollYear,
City: $scope.City,
Country: $scope.Country
};
if ($scope.OperType === 1) {
var promisePost = CRUD_AngularJs_RESTService.post(Student);
promisePost.then(function (pl) {
$scope.StudentID = pl.data.StudentID;
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some error Occured" + err);
});
} else {
//Edit the record
debugger;
Student.StudentID = $scope.StudentID;
var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
promisePut.then(function (pl) {
$scope.Message = "Student Updated Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
};
//To Get Student Detail on the Base of Student ID
$scope.get = function (Student) {
var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.StudentID = res.StudentID;
$scope.Name = res.Name;
$scope.Email = res.Email;
$scope.Class = res.Class;
$scope.EnrollYear = res.EnrollYear;
$scope.City = res.City;
$scope.Country = res.Country;
$scope.OperType = 0;
},
function (errorPl) {
console.log('Some Error in Getting Details', errorPl);
});
}
//To Delete Record
$scope.delete = function (Student) {
var promiseDelete = CRUD_AngularJs_RESTService.delete(Student.StudentID);
promiseDelete.then(function (pl) {
$scope.Message = "Student Deleted Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
});
app.service("CRUD_AngularJs_RESTService", function ($http) {
//Create new record
this.post = function (Student) {
var request = $http({
method: "post",
url: "http://localhost:50028/StudentService.svc/AddNewStudent",
data: Student
});
return request;
}
//Update the Record
this.put = function (StudentID, Student) {
debugger;
var request = $http({
method: "put",
url: "http://localhost:50028/StudentService.svc/UpdateStudent",
data: Student
});
return request;
}
this.getAllStudent = function () {
return $http.get("http://localhost:50028/StudentService.svc/GetAllStudent");
};
//Get Single Records
this.get = function (StudentID) {
return $http.get("http://localhost:50028/StudentService.svc/GetStudentDetails/" + StudentID);
}
//Delete the Record
this.delete = function (StudentID) {
var request = $http({
method: "delete",
url: "http://localhost:50028/StudentService.svc/DeleteStudent/" + StudentID
});
return request;
}
});
})();
Here is the WCF service Code ......
[ServiceContract]
public interface IStudentService
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetAllStudent/")]
List<StudentDataContract> GetAllStudent();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetStudentDetails/{StudentId}")]
StudentDataContract GetStudentDetails(string StudentId);
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/AddNewStudent")]
bool AddNewStudent(StudentDataContract student);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/UpdateStudent")]
void UpdateStudent(StudentDataContract contact);
[OperationContract]
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteStudent/{StudentId}")]
void DeleteStudent(string StudentId);
}
}
Here is Implementation of method of wcf service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCF_REST_Service
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "StudentService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select StudentService.svc or StudentService.svc.cs at the Solution Explorer and start debugging.
public class StudentService : IStudentService
{
StudentManagementEntities ctx;
public StudentService()
{
ctx = new StudentManagementEntities();
}
public List<StudentDataContract> GetAllStudent()
{
var query = (from a in ctx.Students
select a).Distinct();
List<StudentDataContract> studentList = new List<StudentDataContract>();
query.ToList().ForEach(rec =>
{
studentList.Add(new StudentDataContract
{
StudentID = Convert.ToString(rec.StudentID),
Name = rec.Name,
Email = rec.Email,
EnrollYear = rec.EnrollYear,
Class = rec.Class,
City = rec.City,
Country = rec.Country
});
});
return studentList;
}
public StudentDataContract GetStudentDetails(string StudentId)
{
StudentDataContract student = new StudentDataContract();
try
{
int Emp_ID = Convert.ToInt32(StudentId);
var query = (from a in ctx.Students
where a.StudentID.Equals(Emp_ID)
select a).Distinct().FirstOrDefault();
student.StudentID = Convert.ToString(query.StudentID);
student.Name = query.Name;
student.Email = query.Email;
student.EnrollYear = query.EnrollYear;
student.Class = query.Class;
student.City = query.City;
student.Country = query.Country;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return student;
}
public bool AddNewStudent(StudentDataContract student)
{
try
{
Student std = ctx.Students.Create();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.Students.Add(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return true;
}
public void UpdateStudent(StudentDataContract student)
{
try
{
int Stud_Id = Convert.ToInt32(student.StudentID);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
public void DeleteStudent(string StudentId)
{
try
{
int Stud_Id = Convert.ToInt32(StudentId);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
ctx.Students.Remove(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
}
}
Here is HTML CODE ...
#{
Layout = null;
}
<!DOCTYPE html>
<html data-ng-app="RESTClientModule">
<head title="ASAS">
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/MyScripts/Modules.js"></script>
</head>
<body>
<table id="tblContainer" data-ng-controller="CRUD_AngularJs_RESTController">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Year</th>
<th>City</th>
<th>Country</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="stud in Students">
<tr>
<td></td>
<td><span>{{stud.StudentID}}</span></td>
<td><span>{{stud.Name}}</span></td>
<td><span>{{stud.Email}}</span></td>
<td><span>{{stud.Class}}</span></td>
<td><span>{{stud.EnrollYear}}</span></td>
<td><span>{{stud.City}}</span></td>
<td><span>{{stud.Country}}</span></td>
<td>
<input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" />
</td>
<td>
<input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>Student ID</span>
</td>
<td>
<input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Student Name</span>
</td>
<td>
<input type="text" id="sName" required data-ng-model="Name" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Email</span>
</td>
<td>
<input type="text" id="sEmail" required data-ng-model="Email" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Class</span>
</td>
<td>
<input type="text" id="sClass" required data-ng-model="Class" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Enrollement Year</span>
</td>
<td>
<input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>City</span>
</td>
<td>
<input type="text" id="sCity" required data-ng-model="City" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Country</span>
</td>
<td>
<input type="text" id="sCountry" required data-ng-model="Country" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="save" value="Save" data-ng-click="save()" />
<input type="button" id="Clear" value="Clear" data-ng-click="clear()" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Here is screen shot when I run the application..
First, you need to use * in [ServiceContract]. like this:
[WebInvoke(Method = "*"
That way, you allow your method to receive OPTIONS requests.
Then you should add this to your web.config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type, Accept" />
</customHeaders>
</httpProtocol>
Do not forgot to handle OPTIONS requests. Something like this will solve it:
public List<StudentDataContract> GetAllStudent()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
return null;
var query = (from a in ctx.Students
select a).Distinct();
List<StudentDataContract> studentList = new List<StudentDataContract>();
query.ToList().ForEach(rec =>
{
studentList.Add(new StudentDataContract
{
StudentID = Convert.ToString(rec.StudentID),
Name = rec.Name,
Email = rec.Email,
EnrollYear = rec.EnrollYear,
Class = rec.Class,
City = rec.City,
Country = rec.Country
});
});
return studentList;
}
That's it. Good luck.

Issue in returning JSON data showing native code error response

ANGULAR JS
var App = angular.module('myApp', [])
App.controller('mainController', function ($scope, $http) {
$http.get("/Project/getProjects")
.success(function (result) {
$scope.SuccMsg = "SUCCESS.. ";
$scope.projectList = result;
})
.error(function (Data) {
$scope.ErrMsg = "ERROR.. " + Error;
}) })
CONRTOLLER : PROJECT
public JsonResult getProjects()
{
List<Project> p2 = new List<Project>();
p2 = db.Projects.ToList();
return Json(p2,JsonRequestBehavior.AllowGet);
}
HTML FILE
Project
<div ng-controller="mainController">
#*LIST PROJECT*#
<table id="tbl_Project" class="table-striped">
<tr ng-repeat="item in projectList">
<td>{{item.p_name}}</td>
<td>#*DELETE PROJECT*#
<input id="btn_delete" ng-click="deleteProject(item)" value="X" type="button" />
</td>
</tr>
</table>
<br /><br />
<div style="color:firebrick"><b>{{ErrMsg}}</b></div>
<div style="color:forestgreen"><b>{{SuccMsg}}</b></div> </div>

Knockout- Issues editing item with pop up

Im new to knockout and loving it so far. I've been trying to build a row editing grid using a simple table with edit links. So far it seemed to be going great but been stuck on this issue where im getting the errors when tying to save and update or canel:
Uncaught TypeError: this.description is not a function
and
Uncaught TypeError: this.editdescription is not a function
Been staring at the code for several hours now can't seem to wrap my head around this one. I am able to replicate the issue in this JSFIDDLE:
http://jsfiddle.net/N2zNk/49/
Would anyone know what is cloging in my code?
Here is my HTML:
<table>
<tr>
<th>ID</th>
<th>Description</th>
<th>Department</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tbody data-bind="template: { name: 'rowTmpl', foreach: products }"></tbody>
</table>
<script id="rowTmpl" type="text/html">
<tr>
<td data-bind="text: ID"></td>
<td data-bind="text: Description"></td>
<td data-bind="text: Composante"></td>
<td>
Edit
</td>
<td>
Delete
</td>
</tr>
</script>
<!-- popup -->
<div id="dialogEditProduct" style="width: 400px; max-width: 100%;" data-role="popup" data-theme="c" data-overlay-theme="a" data-dismissible="false" data-bind="with: selectedProduct">
<div data-role="header" data-position="inline">
<h1 ></h1>
</div>
<div data-role="content" data-theme="c">
<p>
<label>Description:</label>
<input data-bind="value: editDescription" />
</p>
<p>
<label>Composante:</label>
<input data-bind="value: editComposante" />
</p>
<button data-role="button" data-bind="click: function() { Incidents.pvm.acceptEdit(); }">Save</button>
<button data-role="button" data-bind="click: function() { Incidents.pvm.cancelEdit() }">Cancel</button>
</div>
</div>
Here is my code:
function Item(ID, Description, Composante) {
var self = this;
this.ID = ID;
this.Description = ko.observable(Description);
this.Composante = ko.observable(Composante);
this.editDescription = ko.observable(Description);
this.editComposante = ko.observable(Composante);
this.accept = function () {
this.description(this.editdescription);
this.price(this.editPrice);
return true;
}.bind(this);
//reset to originals on cancel
this.cancel = function () {
this.editdescription(this.description);
this.editComposante(this.Composante);
}.bind(this);
}
Incidents = {
pvm: {},
productStore: {
products: [],
init: function (data) {
this.products = $.map(data, function (product) {
return new Item(product.ID, product.Description, product.Composante);
});
}
},
init: function () {
/*emuluate pulling orders from DB*/
/*this will come from server or local web storage*/
var dataFromServer = [{
ID: "123",
Description: "The server x is unavailable",
Composante: "CCD"
}, {
ID: "124",
Description: "The router located downtown is down",
Composante: "CCDD"
}, {
ID: "125",
Description: "Fiber optic cable downtown is flapping",
Composante: "MIG"
}, {
ID: "126",
Description: "Network unvailable at the beaver site",
Composante: "MIC"
}];
this.productStore.init(dataFromServer);
$(function () {
Incidents.pvm = new Incidents.productViewModel(Incidents.productStore.products);
ko.applyBindings(Incidents.pvm);
$("#productList").listview('refresh');
});
},
productViewModel: function (data) {
var self = this;
var productsArray = [];
if (data && data.length > 0) {
productsArray = data;
}
this.products = ko.observableArray(productsArray);
this.selectedProduct = ko.observable();
this.editProduct = function (productToEdit) {
self.selectedProduct(productToEdit);
// Incidents.pvm.selectedProduct(productToEdit);
};
this.acceptEdit = function () {
var selected = Incidents.pvm.selectedProduct();
if (selected.accept()) {
Incidents.pvm.selectedProduct("");
$('#dialogEditProduct').popup('close');
}
};
this.cancelEdit = function () {
Incidents.pvm.selectedProduct().cancel();
Incidents.pvm.selectedProduct("");
$('#dialogEditProduct').popup('close');
};
}
};
ko.bindingHandlers.jqButton = {
init: function (element) {
$(element).button();
},
update: function (element, valueAccessor) {
var currentValue = valueAccessor();
$(element).button("option", "disabled", currentValue.enable === false);
}
};
ko.bindingHandlers.jqmListView = {
init: function (element) {
$(element).listview();
},
update: function (element, valueAccessor) {
$(element).listview('refresh');
}
};
ko.bindingHandlers.openProductDialog = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$.mobile.changePage("#dialogEditProduct", {
role: 'dialog'
});
$("#dialogEditProduct").open();
// $("#dialogEditProduct").trigger('create');
}
}
};
$.extend({
isNumber: function (obj) {
return !isNaN(parseFloat(obj)) && isFinite(obj);
}
});
Incidents.init();
Javascript is case sensitive. You have mixed up description and Description. Also, editDescription and editdescription.

Categories