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

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.

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:

Angular JS Application Data Binding Failed to Display the Data

I am consuming wcf rest service into angular js application. I am trying to display single record in angular js application based on Account Holder Last Name . when the post the value to wcf service and its receive the values .Its check the values in ado.net code whether the values is valid or invalid . After checking the values ,its able to retrieve Account Holder information in Google chrome network tap response section. But the problem is not displaying anything in webpage .
Here is the Interface .
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetCustomers/{Account_Holder_Last_Name}")]
string GetCustomers(string Account_Holder_Last_Name);
Here is the Implementation .
public string GetCustomers(string Account_Holder_Last_Name)
{
List<object> customers = new List<object>();
string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Holder_Last_Name =#Account_Holder_Last_Name";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Parameters.AddWithValue("#Account_Holder_Last_Name", Account_Holder_Last_Name);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
while (sdr.Read())
{
customers.Add(new
{
Tittle = sdr["Tittle"],
Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
Account_Holder_DOB = sdr["Account_Holder_DOB"],
Account_Holder_House_No = sdr["Account_Holder_House_No"],
Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],
Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
Account_Number = sdr["Account_Number"]
});
}
}
}
conn.Close();
}
return (new JavaScriptSerializer().Serialize(customers));
}
}
Here is the Script code .
#{
Layout = null;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.IsVisible = false;
$scope.Customers = [];
$scope.Search = function () {
var post = $http({
method: "GET",
url: "http://localhost:52098/HalifaxIISService.svc/GetCustomers/" + encodeURIComponent($scope.Account_Holder_Last_Name),
dataType: 'json',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
});
post.success(function (data, status) {
$scope.Customers = eval(data.d);
$scope.IsVisible = true;
},
function (err) {
console.log("Some Error Occured." + err);
}
);
post.error(function (data, status) {
$window.alert(data.Message);
});
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Account_Holder_Last_Name" />
<input type="button" value="Submit" ng-click="Search()" />
<hr />
<table cellpadding="0" cellspacing="0" ng-show="IsVisible">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th> Tittle</th>
<th>First Name</th>
<th> Last Name</th>
<th> DOB </th>
<th> House No</th>
<th> Street Name</th>
<th>Post Code</th>
<th> Occupation</th>
<th>Account Number</th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td>{{m.Tittle}}</td>
<td>{{m.Account_Holder_First_Name}}</td>
<td>{{m.Account_Holder_Last_Name}}</td>
<td>{{m.Account_Holder_DOB}}</td>
<td>{{m.Account_Holder_House_No}}</td>
<td>{{m.Account_Holder_Street_Name}}</td>
<td>{{m.Account_Holder_Post_Code}}</td>
<td>{{m.Account_Holder_Occupation}}</td>
<td>{{m.Account_Number}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Here is the screen shot wcf service receiving the values .
Here is the screen shot Google chrome network tab able to catch the data and web page does not displaying the data .

My angular method does not fire

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

How to make a dynamique form of search

I'm developping a web application for searching media, so for my interface of search i should have somthing like that : the user specify the 4 fields and he can add an other fields(the same fields nature but he want to add an other criterion) by clicking on the icon Plus, i have done that with jquery, see the image below:enter image description here
But my problem is that: How can i pass the liste of form values to my action!!
here you are the code of my controller and my view (i do it just for one )
Controller:
[HttpPost]
public ActionResult RechercheForm(Recherche FormData)
{
List<Asset> liste = null;
if (FormData.Op == "Like")
{
if (FormData.Critere == "Titre")
{
liste = bdd.Assets.Where(a => (a.Titre.Contains(FormData.Val1)
)).ToList();
ViewBag.Val = FormData.Val1;
return View("Index",liste);
}
else
if (FormData.Critere == "TitreCourt")
{
liste = bdd.Assets.Where(a => (a.TitreCourt.Contains(FormData.Val1)
)).ToList();
return View("Index", liste);
}
}
return View("Index");
}
View:
<div class="right-content" style="width: 760px;" >
<!-- DropListDownData -->
#{
Dictionary<string, string> ListCritere=new Dictionary<string, string>
{
{"Titre", "Titre"},
{"TitreCourt", "TitreCourt"},
// some lines skipped
};
Dictionary<string, string> ListOp = new Dictionary<string, string>
{
{"Like", "Like"},
{"Sup", "Sup"},
{"Inf", "Inf"},
// some lines skipped
};
}
#using (Html.BeginForm("RechercheForm", "Recherche",new { ReturnUrl = ViewBag.ReturnUrl },FormMethod.Post, new { #class = "form-inline" })){
<button type="submit" class="btn btn-default">Rechecrcher</button>
<table id="TableRech">
<tr>
<th>Critere</th>
<th>Opérateur</th>
<th>Valeur1</th>
<th>Valeur2</th>
<th></th>
</tr>
<tr>
<td><div class="form-group">
#Html.DropDownList("Critere", new SelectList(ListCritere, "Key", "Value"),new { #class = "form-control" })
</div></td>
<td><div class="form-group">
#Html.DropDownList("Op", new SelectList(ListOp, "Key", "Value"),new { #class = "form-control" })
</div></td>
<td><div class="form-group">
#Html.TextBox("Val1",null,new {id = "Val2", #class = "textbox", style="width:50px;padding-right: 50px; " })
</div></td>
<td> <div class="form-group">
#Html.TextBox("Val2",null,new {id = "Val2", #class = "textbox", style="width:50px;padding-right: 50px; " })
</div></td>
<td><span class="glyphicon glyphicon-plus-sign" id="Plus" style="width: 15px;" onclick="RechFunctionPlus()" ></span></td>
</tr>
</table>
}
</div>
</div>
<script>
function RechFunctionPlus() {
var table= document.getElementById('TableRech');
var tr = document.createElement('tr');
table.appendChild(tr);
var td = document.createElement('td');
td.innerHTML='<select class="form-control" id="Critere" name="State"> <!-- some attrs=ibutes skipped --><option value=""></option><option value="Titre">Titre</option><option value="TitreCourt">TitreCourt</option><option value="Type">Type</option></select>';
tr.appendChild(td);
var td2 = document.createElement('td');
td2.innerHTML='<select class="form-control" id="Op" name="State"> <!-- some attrs=ibutes skipped --><option value=""></option><option value="Like">Like</option><option value="Inf">Inf</option><option value="Sup">Sup</option></select>';
tr.appendChild(td2);
var td3 = document.createElement('td');
td3.innerHTML='#Html.TextBox("Val1",null,new {id = "Val1", #class = "textbox", style="width:50px;padding-right: 50px; " })';
tr.appendChild(td3);
var td4 = document.createElement('td');
td4.innerHTML='#Html.TextBox("Val2",null,new {id = "Val2", #class = "textbox", style="width:50px;padding-right: 50px; " })';
tr.appendChild(td4);
var td5 = document.createElement('td');
td5.innerHTML='<span class="glyphicon glyphicon-minus-sign" id="Plus" style="width: 15px;" onclick="RechFunctionMoins()" ></span>';
tr.appendChild(td5);
}
</script>
i think to do a list of the calss "Recherche" that i will pass it to my Action "RechercheForm" but i don't how?!!
Use JavaScript
For example:
function sendForm(projectId, target) {
$.ajax({
url: target,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
projectId: projectId,
userAccountIds: [1, 2, 3]
}),
success: ajaxOnSuccess,
error: function (jqXHR, exception) {
alert('Error message.');
}
});
}
See this post Post JavaScript array with AJAX to asp.net MVC controller

Save image path in database using angularjs

I Have uploaded my image in local folder using angular file-model and returning the path using json but i am unable to save the path to database. Please help me to solve this issue. I am using .success method to return the response data to a hidden field to store it in database but it shows ERROR:" Cannot read property 'success' of undefined ".
services.js:
service.UploadFile = function (file) {
var fd = new FormData();
fd.append('file', file);
$http.post('/Empdet/UploadFile', fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
})
.error(function () {
});
}
return service;
Controller.js:
$scope.UploadFile = function () {
console.log('UploadFile');
console.log($scope.Empdet.PhotoFile);
EmployeeFactory.UploadFile($scope.Empdet.PhotoFile).success(function (response) {
console.log('response.IsSuccessful');
console.log(response.Data);
$scope.IsSuccessful = response.IsSuccessful;
if ($scope.IsSuccessful) {
$scope.PhotoText = response.Data;
console.log('$scope.PhotoText');
console.log($scope.PhotoText);
$scope.CanClearMessage = true;
} else {
$scope.SuccessMessage = '';
$scope.ErrorMessage = response.ReasonForFailure;
$scope.CanClearMessage = true;
}
}
)};
CreateNewEmployee.cshtml:
<tr>
<td style="text-align: left;">
<label class="labelsytle">
PhotoFile
</label>
</td>
<td style="text-align: left;">
<input class="form-control" type="file" file-model="Empdet.PhotoFile" style="border-radius: 5px;"/>
<td><button class="btn btn-primary" ng-click="UploadFile()" style="border-radius: 5px; font-family: Consolas;">UPLOAD</button></td>
</td>
</tr>
<tr>
#*<td style="text-align: left;">
<label class="labelsytle">
PhotoText
</label>
</td>*#
<td style="text-align: left;">
<input class="form-control" type="hidden" name="search" ng-model="Empdet.PhotoText" placeholder="Enter PhotoText" style="border-radius: 5px;" />
</td>
</tr>
EmpdetController.cs:
[HttpPost]
public ActionResult UploadFile()
{
var file = Request.Files[0];
var path = Path.Combine(Server.MapPath("~/Photos/") + file.FileName);
file.SaveAs(path);
// prepare a relative path to be stored in the database and used to display later on.
path = Url.Content(Path.Combine("~/Photos/" + file.FileName));
// save to db
return Json(path.ToString(), JsonRequestBehavior.AllowGet);
}
Use .then function instead of .success
Replace your .success and .error code block with below code
.then(function (d) {
//Success callback
}, function (error) {
//Failed Callback
alert('Error!');
});

Categories