I'm trying to pass data stored in a dynamically created table to the server, and while I can access the data in my angularJS controller, I am having difficulty learning how to pass this data to the server to process.
Here is my angularjs function that is able to access my table data, its just passing the data and calling my vb.net function that I am having trouble with.
$scope.requestThatCertificatesBeEmailed = function () {
for (index = 0; index < $scope.requests.length; ++index) {
alert('For loop entered')
var submittedEmailAddressString = $scope.requests[index].emailAddress;
var submittedCertificateTypeString = $scope.requests[index].certificateType;
var submittedSearchTypeString = $scope.requests[index].searchType;
var submittedSearchString = $scope.requests[index].submittedNumbers;
alert(submittedSearchTypeString);
$http.post("/Home/NewTextFile", { submittedEmailAddress: submittedEmailAddressString, submittedCertificateType: submittedCertificateTypeString, submittedSearchType: submittedSearchTypeString, submittedSearch: submittedSearchString }).error(function () {
$scope.requests = [];
});
You will need to post/put the data back to the server. If you are working in a ASP.NET WebForms application, you will likely need to pass the value as JSON to the server in a hidden input field. If you are working in an ASP.NET MVC application, you should be able to invoke a controller action sending in the JSON table data from javascript.
Your action method in your MVC Controller should look like this:
<HttpPost> _
Public Function NewTextFile(submittedEmailAddress As String, submittedCertificateType As String, submittedSearchType As String, submittedSearch As String) As ActionResult
'do some work
End Function
Using jQuery, you could invoke the controller action like so:
$.ajax({
url: '/Home/NewTextFile',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
submittedEmailAddress: submittedEmailAddressString,
submittedCertificateType: submittedCertificateTypeString,
submittedSearchType: submittedSearchTypeString,
submittedSearch: submittedSearchString
}),
processData: false,
dataType: 'json'
});
Below is an AngularJS example I whipped together:
On/referenced from the View:
<script type="text/javascript">
angular.module('httpExample', [])
.controller('ContactController', ['$scope', '$http',
function ($scope, $http, $templateCache) {
$scope.contact = { userName: '', firstName: '', lastName: '' };
$scope.get = function () {
$scope.code = null;
$scope.response = null;
$http.get('/Home/Contact').
success(function (data, status) {
$scope.status = status;
$scope.data = data;
$scope.contact = data;
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.contact = { userName: '', firstName: '', lastName: '' }
$scope.status = status;
});
};
$scope.post = function () {
$scope.code = null;
$scope.response = null;
$http.post('/Home/Contact', $scope.contact).
success(function (data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}]);
</script>
Somewhere in the body:
<div>
<div ng-app="httpExample">
<div ng-controller="ContactController">
<fieldset>
<legend>Contact</legend>
Username: <input type="text" ng-model="contact.userName"/><br/>
Last Name: <input type="text" ng-model="contact.lastName"/><br/>
First Name: <input type="text" ng-model="contact.firstName"/><br/>
</fieldset>
<br />
<button id="getbtn" ng-click="get()">get</button>
<button id="postbtn" ng-click="post()">post</button><br/><br/>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</div>
</div>
And your MVC server side Home controller has methods that look like this:
<HttpGet> _
Public Function Contact() As JsonResult
Dim contact = New With { .userName = "smithjk", .firstName = "John", .lastName = "Smith" }
Return Json(contact, JsonRequestBehavior.AllowGet)
End Function
<HttpPost> _
Public Function Contact(userName As String, firstName As String, lastName As String) As ActionResult
'do some work
System.Diagnostics.Debug.Print(userName)
Return New EmptyResult()
End Function
Related
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>
I am getting this strange behavior in jQuery when working with mvc application.
Below is MVC view in which I have implemented Text change event,
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserId, "", new { #class = "text-danger" })
$("#UserId").change(function () {
var UserId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetValidUserName',
type: 'POST',
data: JSON.stringify({ UserId: UserId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
While debugging application when I load Index view directly first time , jQuery function gets called and invoke the controller action properly.http://localhost:51012/UserApplication/Index
But when I load the view again, jQuery function doesn't get called.
Controller code,
public JsonResult GetValidUserName(string userId)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string UserID = "";
objLMT.UserList = objLMTDAL.GetAll_User("", 0, "6");
var AllUsersInDatabase = from p in objLMT.UserList
where p.UserId == userId
select new
{
Name = p.UserName,
Id = p.UserId,
};
foreach (var user in AllUsersInDatabase)
{
if (user.Name != null)
{
UserID = user.Id;
}
}
return Json(UserID, JsonRequestBehavior.AllowGet);
}
You have several issues with AJAX callback:
1) type: 'POST' option requires [HttpPost] attribute. If the attribute isn't present on the action method, use type: 'GET' instead.
2) You don't need JSON.stringify() to pass single parameter containing simple types (numeric and string values). A simple { userId: UserId } should be fine.
3) The controller action's parameter name must be exactly match with parameter name sent from AJAX callback.
Therefore, your AJAX callback should be follow example below:
$(function () {
$("#UserId").change(function () {
var UserId = $(this).val();
$.ajax({
url: '#Url.Action("GetValidUserName", "ControllerName")',
type: 'GET',
data: { userId: UserId },
dataType: 'json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
});
I am trying to make a trivial call to a SQL Server 2000 database using Angular's $http service. Angular factory containing the $http:
var RegistrationFactory = function ($http, $q, SessionService) {
return function (email, password, confirmPassword) {
var result = $q.defer();
$http({
method: 'POST',
url: SessionService.apiUrl + '/api/Account/Register',
data: { Email: email, Password: password, ConfirmPassword: confirmPassword },
headers: { 'Content-Type': 'application/json' }
})
.success(function (response) {
result.resolve(response);
})
.error(function (response) {
result.reject(response);
});
return result.promise;
}
}
RegistrationFactory.$inject = ['$http', '$q', 'SessionService'];
And inside the AccountController:
[HttpPost]
[AllowAnonymous]
public async Task<bool> Register(RegisterViewModel model)
{
string queryString = "INSERT INTO Northwind VALUES('test', 'values')";
SqlConnection cnxn = new SqlConnection(WebConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand(queryString, cnxn);
cnxn.Open();
command.ExecuteNonQuery();
cnxn.Close();
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
var result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return false;
}
await SignInManager.SignInAsync(user, false, false);
return true;
}
This program is merely trying to show that the SQL-related codes are executed upon the RegistrationFactory being utilized.
The Register.cshtml view:
<form ng-submit="register()">
<label for="emailAddress">Email Address:</label>
<input id="emailAddress" type="text" ng-model="registerForm.emailAddress" required />
<label for="password">Password:</label>
<input id="password" type="password" ng-model="registerForm.password" required />
<label for="confirmPassword">Password:</label>
<input id="confirmPassword" type="password" ng-model="registerForm.confirmPassword" required />
<button type="submit">Register</button>
</form>
And the RegisterController.js that handles above view:
var RegisterController = function ($scope) {
$scope.registerForm = {
emailAddress: '',
password: '',
confirmPassword: '',
registrationFailure: false
};
$scope.register = function () {
var result = RegistrationFactory($scope.registerForm.emailAddress, $scope.registerForm.password, $scope.registerForm.confirmPassword);
result.then(function (result) {
if (result.success) {
$location.path('/routeOne');
} else {
$scope.registerForm.registrationFailure = true;
}
});
}
}
RegisterController.$inject = ['$scope', '$location', 'RegistrationFactory'];
I am trying to figure out how to actually execute the statement as the result of my $http. Additionally, being able to pass data through the 'POST' would be awesome. And, yes, it has to be for SQL Server 2000, so Entity Framework is not an option. Thanks, everyone!
I'm facing a strange issue with autocomplete.
First issue:
based on the tutorial found here, only the first letter of the found items is showing in the list of autocomplete items
Here is an illustration:
My action at debug time
Dummy data returned, always the same regardless of the search pattern just for testing
In the rendered view, this is what happens:
The Javascript for autocomplete of this scenario is as follows:
$("#Email").autocomplete('#Url.Action("FindEmail", "Administration")',
{
dataType: 'json',
parse: function(data) {
var rows = new Array();
for (var i = 0; i < data.length; i++) {
rows[i] = {
data: data[i].Value,
value: data[i].Value,
result: data[i].Value
};
}
return rows;
},
width: 300,
minLength: 3,
highlight: false,
multiple: false
});
Second issue:
I've changed my code to work with a more comfortable Ajax call for me that depends on Model mapping rather than sending a q and limit parameters as in the previous tutorial, and as I've seen in many other tutorials, but the Ajax call isn't firing, not even giving me an error.
My code for this scenario is based on this Stack Overflow Answer
Here is my controller and view code related:
//[HttpPost]
[SpecializedContextFilter]
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult FindEmail(RegistrationModel model) //Notice the use of model instead of string q and string limit
{
//Just a dummy implementation
var rez = new List<ValueModel>
{
new ValueModel {Description = "atest1#test.com", Value = "atest1#test.com"},
new ValueModel {Description = "atest2#test.com", Value = "atest2#test.com"},
new ValueModel {Description = "atest3#test.com", Value = "atest3#test.com"},
new ValueModel {Description = "atest4#test.com", Value = "atest4#test.com"}
};
//var retValue = rez.Select(r => new { email = r.Value }).OrderBy(x => x).Take(10);
//return Json(retValue, JsonRequestBehavior.AllowGet);
return Json(rez, JsonRequestBehavior.AllowGet);
}
View JavaScript:
$("#Email").autocomplete({
source: function(request, response) {
$.ajax({
url: '#Url.Action("FindEmail", "Administration")',
type: "POST",
dataType: "json",
data: { email: $("#Email").val(), conferenceId: $("#ConferenceId").val() },
success: function(data) {
response($.map(data, function(item) {
return { label: item.Value, value: item.Value, id: item.Value };
}));
},
select: function(event, ui) {
$("input[type=hidden]").val(ui.item.id);
}
});
}
});
Firefox console view:
I've tried a lot of codes for the second scenario, most of them are Stack Overflow answers, but nothing is happening!
I'm my missing anything ?
Note: jQuery plugins are included, Ajax is already working in the same page, so I'm not sure whats the problem
Thanks for any help.
Here is a full working example, see screen grab.
These are the steps that I had take to get the second example working.
Script-references/Markup/Js
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<input id="ConferenceId" value="1" />
<div class="ui-widget">
<label for="Email">Email: </label>
<input id="Email">
</div>
<script type="text/javascript">
$("#Email").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("FindEmail", "Administration")',
type: "POST",
dataType: "json",
data: { email: $("#Email").val(), conferenceId: $("#ConferenceId").val() },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Value, value: item.Value, id: item.Value };
}));
},
select: function (event, ui) {
$("input[type=hidden]").val(ui.item.id);
}
});
}
});
</script>
Models
public class RegistrationModel
{
public string Email { get; set; }
public string ConferenceId { get; set; }
}
public class ValueModel
{
public string Description { get; set; }
public string Value { get; set; }
}
Controller Action
I had to add the [HttpPost] attribute.
[HttpPost]
public JsonResult FindEmail(RegistrationModel model) //Notice the use of model instead of string q and string limit
{
//Just a dummy implementation
var rez = new List<ValueModel>
{
new ValueModel {Description = "atest1#test.com", Value = "atest1#test.com"},
new ValueModel {Description = "atest2#test.com", Value = "atest2#test.com"},
new ValueModel {Description = "atest3#test.com", Value = "atest3#test.com"},
new ValueModel {Description = "atest4#test.com", Value = "atest4#test.com"}
};
return Json(rez, JsonRequestBehavior.AllowGet);
}
Screen grab
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.