Passing data from view to net-mvc controller using AngularJS - asp.net

public class Home
{
string CustEmail { get;set;}
string CustName { get; set;}
int id { get; set;}
}
Model
[HttpPost]
public void CreateCustomer(Home cust)
{
if (ModelState.IsValid)
{
}
}
Controller
angular.module('myFormApp', []).controller('CustomerController', function ($scope, $http, $location, $window) {
debugger;
$scope.cust = {};
$scope.message = '';
$scope.result = "color-default";
$scope.isViewLoading = false;
//get called when user submits the form
$scope.submitForm = function () {
$scope.isViewLoading = true;
console.log('Form is submitted with:', $scope.cust);
//$http service that send or receive data from the remote server
var cust = {
CustEmail: $scope.cust.CustEmail,
CustName: $scope.cust.CustName,
id: 1,
};
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
}).then(function (data, status, headers, config) {
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
})
$scope.isViewLoading = false;
}
}).config(function ($locationProvider) {
//default = 'false'
$locationProvider.html5Mode(true);
});
I get the data in the proper format in front-end and the post-back call is also working but I cannot get value in MVC controller. I don't know what am I doing wrong. I have tried using the individual item in controller then it's working fine but i want it through model only.

The .then method of a promise only exposes one value, not four values.
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
})
For more information, see
AngularJS $http Service API Reference - returns
UPDATE
You can add a .catch block to console log any errors:
$http(
{
method: 'POST',
url: '/Home/CreateCustomer',
data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
var data = response.data;
var status = response.status;
var headers = response.headers;
var config = response.config;
$scope.errors = [];
if (data.success === true) {
$scope.cust = {};
$scope.message = 'Form data Submitted!';
$scope.result = "color-green";
$location.path(data.redirectUrl);
$window.location.reload();
}
else {
$scope.errors = data.errors;
}
console.log("OK:", response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});

Related

XML pasing Error: no root element found in location when i try to pass data to action of controller asp.net mvc application

when i pass data to the first action its working fine and based on the return of that action i call another one with another ajax post request and pass the same data but the error message appears on console and nothing happens, note that if i don't pass data at all(not in the same nor the second query) both actions get called without problem but with no data passed enter image description here
those are the codes for the actions and the script(second)
[HttpPost]
public async Task<bool> Check(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
var testAuthResult = authResult;
return authResult.force;
}
[HttpPost]
public async Task<IActionResult> LoginV2(string login = "", string password = "")
{
var model = new HomeViewModel()
{
LoginRequest = new LoginRequest()
{
Login = login,
Password = password,
}
};
var test = model;
var authResult = await _accountUseCases.LoginAsync(model).ConfigureAwait(false);
if (!authResult.result)
{
model.LoginRequest.Password = "";
TempData["Message"] = authResult.message;
return RedirectToAction("Index", "Login", model);
}
if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Trainings");
}
public IActionResult IndexV2()
{
return View();
}
and this is the script
#using System.Text.Encodings.Web
#using Microsoft.AspNetCore.Mvc.Localization
#using Microsoft.Extensions.Localization
#using UI
#inject IViewLocalizer Localizer
#inject IStringLocalizer<SharedResource> SharedLocalizer
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions {
private string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<script type="text/javascript" nonce="bGFsYWNvY29qYW1ib2xhbGF5ZWFhYWE=">
$(document).on("click", "#LoginFormSubmit",
function (e) {
setLoginCredentials();
})
function GetLoginCredentials() {
var login = document.getElementById("txtUsername2").value;
var pwd = document.getElementById("Password").value;
var data = {
'login': login,
'password': pwd
};
//var jData = JSON.stringify({ login: login, password: pwd });
//return jData
return data ;
}
function setLoginCredentials() {
var data = GetLoginCredentials();
console.log(data);
$.ajax({
type: "POST",
url: "#Url.Action("Check", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
//contentType: "application/json; charset=utf-8",
//dataType: "json",
//data: JSON.stringify({login:data.login, password: data.password}),
data: data,
success: function (result, status, xhr) {
if (result == true) {
$('#LoginConfirmationModal').modal('show');
}
else if(result == false) {
//var data2 = GetLoginCredentials();
$.ajax({
type: "POST",
url: "#Url.Action("LoginV2", "Login")",
headers: {
"RequestVerificationToken": "#GetAntiXsrfRequestToken()"
},
data: data,
//contentType: "application/json",
//dataType: "json",
//data: JSON.stringify({ login: data.login, password: data.password }),
//data:JSON.stringify({login:data2.login , password:data2.password}),
//contentType:"application/json;charset=utf-8",
//dataType:"json",
success: function (result, status, xhr) {
},
error: function (xhr, status, error) {
}
});
}
}
,
error: function (xhr, status, error) {
}
});
};
</script>

Return created item key

My app creates a new item, and I want to retrieve the key to use in a server script. The data variable returns null though. This is what I have:
function addItem(addButton) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function(key) {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
return newProjectItem;
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
var data = app.datasources.ProjectItems.item._key;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}
This is not neat by any means, but I fixed it by creating a new function:
function addItem(addButton, key) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function() {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
var key = newProjectItem._key;
value(key);
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
function value(record){
var data = record;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}
}

Handling multiple ajax call using $q.all

I'm trying to call multiple ajax in my page using $q. after all the response am storing in one array. but it seems not working correctly-
My controller-
used for loop to go over multiple pages in API and get the json.
$scope.items = [];
for (var i = 1; i < 10; i++) {
var apiURL = "https://swapi.co/api/planets?page =" + i;
searchData(apiURL).then(function(response) {
$scope.items.push(response[0].data.results);
});
}
$scope.showDetail = function(data) {
$scope.items = data.results;
$scope.items.sort(function(a, b) {
return a.population.localeCompare(b.population);
});
}
$scope.showDetail($scope.items);
$scope.highlighFont = function() {
}
My Factory-
var app = angular.module('starApp');
app.factory('searchData', function($q, $http) {
return function(apiUrl) {
var promises = [];
var deffered = $q.defer();
$http({
method : 'GET',
url : apiUrl
}).then(function(data) {
deffered.resolve(data);
}, function(error) {
deffered.reject();
})
promises.push(deffered.promise);
return $q.all(promises);
}
});
can someone correct me if am doing wrong??
You need to call $q.all() in the controller
app.factory('searchData', function($q, $http) {
return function(apiUrl) {
return $http({
method : 'GET',
url : apiUrl
});//$http returns a promise
}
});
controller:
$scope.promises = [];
for (var i = 1; i < 10; i++) {
var apiURL = "https://swapi.co/api/planets?page =" + i;
$scope.promises.push(searchData(apiURL));
}
$q.all($scope.promises).then(function(results){
console.log(results);
});

How to response from servlet to YUI?

I send io to server with YUI and how to respond back to YUI?
Here is code :
var user = {
userName: username,
password: password,
customerId: customerId
};
var success = function (ioId, o) {
responseContent = Y.JSON.parse(o.responseText);
if (responseContent.code == 0) {
window.location = 'Home.jsp';
}
};
var failure = function (ioId, o) {
//do something
};
var cfg = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
sync: false,
data: user,
on: {
'success': success,
'failure': failure
}
};
new Y.IO().send("http://localhost:7778/web/LoginController", cfg);
Redirect not work and i decide to redirect by YUI. Thanks!!!
var success = function (ioId, o) {
responseContent = Y.JSON.parse(o.responseText);
if (responseContent.code == 0) {
window.location = 'Home.jsp';
}
//Like this?
responseDiv.innerHTML = responseContent.yourData;
};

MVC3 JSON Return to Edit Page

So I have some javascript code that sends data to my controller:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("#newGrade").click(function () {
var newGradeName = $("#newGradeName").val();
var newGradeValue = $("#newGradeValue").val();
var vSchoolID = $("#SchoolID").val();
if (newGradeName != null && newGradeValue != null) {
$.ajax({
url: '#Url.Action("NewGrade", "School")',
data: { gradeName: newGradeName, gradeValue: newGradeValue, schoolID: vSchoolID },
type: 'POST',
traditional: true,
success: function (data) {
if (data.status)
window.location = data.route;
},
error: function () {
return false;
}
});
}
});
});
</script>
Controller:
public ActionResult NewGrade(String gradeName, Int32 gradeValue, Guid schoolID)
{
School school = schoolRepository.GetByID(schoolID);
school.Grades.Add(
new Grade
{
GradeID = Guid.NewGuid(),
Name = gradeName,
NumericalValue = gradeValue
});
schoolRepository.Update(school);
schoolRepository.Save();
if (Request.IsAjaxRequest())
{
var json = new { status = true, route = Url.RouteUrl(new { action = "Edit", id = schoolID }) };
return Json(json, JsonRequestBehavior.AllowGet);
}
return View();
}
My issue now is I want to return to my Edit page (possibly refreshing the page, but not the data, or just refresh the entire page), but my Edit page takes an ID (schoolID). Shown here when pressing the button to get to the Edit page:
<i class="icon-pencil"></i> Edit
Try window.location.href and see what happens.
success: function(data) {
if (data.status)
window.location.href = data.route;
},
This should work fine assuming you are getting a JSON reponse from your action method like
{"status":"true","route":"/School/Edit/1"}
where 1 is the ID of new record.

Resources