I have a method that return json data to my mvc view, not sure why my view shows json data instead of what I have in success part. This is my Post method:
[HttpPost]
[Route("resetpassword")]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel resetPasswordViewModel)
{
...
if (ModelState.IsValid)
{
if (resetPasswordViewModel.Password == resetPasswordViewModel.ConfirmPassword)
{
var user = Task.Run(() => Service.GetUserByEmailAsync(email)).Result;
if (user != null)
{
userRequest.Id = user.FirstOrDefault().Id;
userRequest.Password = resetPasswordViewModel.Password;
userRequest.Token = token;
await Service.UpdateUserAsync(userRequest);
}
}
else
{
return Json(new { status = "error", message = "Please enter the same value again" });
}
}
return Json(new { status = "success", message = "" });
}
This is my view that is modal:
#model Models.ResetPasswordViewModel
#if (Model != null)
{
<div class="page resetPassword">
#using (Html.BeginForm("resetpassword", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal" id="reset-password">
<div class="modal-content">
<span class="close">X</span>
<div><input type="email" name="email" id="email" readonly value=#Model.Email /></div>
<div class="create-user-label">Password</div>
....
and this is my ajax function:
function resetPassword() {
var postResult = null;
var data = {
Email: document.getElementById('email').value
};
var path = "/resetpassword";
var errorMessage = document.getElementById('Message');
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
postResult = $.parseJSON(result);
alert(postResult.data);
if (result && result.message) {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});
}
but instead of my view I only see json data in my screen like:
{"status":"success","message":""}
Your data will be automatically converted from JSON format into Javascript objects.
Presumably you just want to display the message in an alert:
success: function (result)
{
alert(result.data.message);
},
Well your data is going through, looks like you have some mapping problems, you should try this.
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
alert(result['status']);
if (result['status']== 'success') {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});
Related
The scenario is, I need to set the value of the dropdown (ng-select2) when a user presses on edit button present on the page. I am using ajax to fetch the options. The code is in angular.
I took reference from : https://github.com/tealpartners/ng-select2
<div class="form-div">
<label for="uploader">Select Uploader<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="uploader" id="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
<div class="form-div">
<label for="uploader">Select Approver<span class="asterick-red">*</span>
</label>
<ng-select2 formControlName="approver" [id]="uploader" [options]="select2Options" width="270">
</ng-select2>
</div>
</div>
setSelect2Options() {
this.select2Options = {
triggerChange: true,
allowClear: true,
placeholder : 'Select User* ',
minimumInputLength: 3,
ajax: {
url: '/api/reward/uploader/approver/search/user?limit=15',
headers: {
'X-XSRF-TOKEN': sessionStorage.getItem("auth"),
'content-type': 'application/json'
},
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term, page) {
return {
q: term.term, // search term
_: term._type
};
},
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
id: item.id,
text: item.name + " - " + item.email
}
})
};
}
},
//[placeholder]="'Select User* '"
}
}
The above codes are well and good. But now on a button click i need to set a value inn the select box.
this.vcDataService.getUploaderAproverDetails(id).subscribe((res: any) => {
this.uploaderApproverForm.controls['approver'].setValue(res.approverDetails.uploaderUserId);
this.uploaderApproverForm.controls['uploader'].setValue(res.uploaderDetails.approverUserId);
console.log("134", res)//uploaderUserId
//this.select2Options.ajax.processResults.push({id: 103, text: "aa"})
this.select2Options.placeholder="aa";
//this.displayUploader = "aaa";
// $('#uploader').val('ENABLED_FROM_JS');
// $('#uploader').trigger('change');
// this.select2Options.templateSelection = {
// selected: true,
// id: res.approverDetails.approverUserId,
// text: res.approverDetails.approverName,
// title: res.approverDetails.approverName
// }
// this.select2Options.initSelection = {
// callback: {
// data: {"id":103, "text":'ENABLED_FROM_JS'}
// }
// }
console.log(this.select2Options);
this.updateApproverUploader = true;
this.uploaderApproverId = res.uploaderApproverId;
this.cd.detectChanges();
},
err => {
Swal.fire('Oops...', err.error.err, 'error');
})
I tried few things but didn't got the workaround.
After going through the documentation I found a solution for it. I used the data attribute of the ng-select2 and assigned it to a Select2OptionData type variable.
import { Select2OptionData} from 'ng-select2';
patch_panel_array: Select2OptionData[];
Then I added the required data which I needed to show in the field as displayed below:
res.panelApprovers.map(item => {
this.patch_panel_array.push({
id: item.panelApproverUserId,
text: item.panelApproverUserName + " - " + item.panelApproverUserEmail
})
approverIds.push(String(item.panelApproverUserId));
});
this.formData.controls['panelApprover'].setValue(approverIds);
And here is my select 2 field:
<ng-select2 formControlName="panelApprover" [data]="patch_panel_array" [options]="select2OptionsPanel" width="100%" style="width: 100%;">
</ng-select2>
I have this method in a controller to reset the password of a user by mail.
public JsonResult RecoverPasswordByEmail(string mail)
{
MembershipUser member = Membership.GetUser(Membership.GetUserNameByEmail(mail));
string newPassword = System.Web.Security.Membership.GeneratePassword(14, 0);
member.UnlockUser();
if (!member.ChangePassword(member.ResetPassword(), newPassword))
{
return Json(new { Resultado = false, Excepcion = "Couldn't change password" }, JsonRequestBehavior.AllowGet);
}
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress("foo#bar.com");
System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(mail);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);
message.Subject = "Forgot pass";
if (member.IsLockedOut)
{
message.Body = "You're locked";
}
else
{
message.Body = "New password: " + newPassword;
}
var client = new System.Net.Mail.SmtpClient("my.smtpserver.com", 587)
{
Credentials = new System.Net.NetworkCredential("foo#bar.com", "12345"),
EnableSsl = true
};
try
{
client.Send(message);
}
catch (System.Net.Mail.SmtpException ex)
{
return Json(new { Resultado = false, Excepcion = ex.Message }, JsonRequestBehavior.AllowGet);
}
return Json(new { Resultado = true }, JsonRequestBehavior.AllowGet);
}
I do an ajax request using jQuery from a button in a dialog from the login View.
The weird thing is that I use another controller method RecoverPassword that does the same thing but by the username and that works. Using firebug I see that RecoverPassword does the job and returns a JSON with the result, but RecoverPasswordByEmail responds with a big html document.
The important part of the HTML:
<div id="dialog">
<h2>Retrieve Password</h2>
#Html.Label("Mail:")<br/>
#Html.TextBox("txtMail")
<div id="loading">
<br/><img class="displayed" src="#Url.Content("~/Content/Images/Ajax/ajax-loader3.gif")" alt="loading" /><br/>
#Html.Label("Error")
</div>
<br/><br/><input class="button" id="btnSendMail" type="submit" value="Get new password" />
<div>
Recuperar contraseƱa
</div>
</div>
And the js:
$(document).ready(function () {
var requestMail;
$('#btnSendMail').button();
$('#loading').hide();
$("label[for=Error]").text("");
$('#btnSendMail').click(function (event) {
event.preventDefault();
var mail = $("#txtMail").val();
if (mail.length > 0) {
if (requestMail && requestMail .readystate != 4) {
requestMail .abort();
}
$('#loading').show();
$('input[id="btnSendMail"]').attr('disabled', 'disabled');
requestCorreo = $.ajax({
url: '/Users/RecoverPasswordByEmail',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
timeout: 8000,
data: { Email: mail },
success: function (response) {
if (response.Result) {
$("label[for=Error]").text('New password has been sent to: ' + mail);
}
else {
alert(response.Result + ' ' + response.Exception);
}
},
error: function (xhr, textStatus, thrownError) {
if (textStatus === "timeout") {
alert("got timeout");
}
else {
alert(xhr.status + ' ' + textStatus + ' ' + thrownError);
}
},
complete: function () {
$('#loading').hide();
$('input[id="btnSendMail"]').removeAttr('disabled');
}
});
}
else {
$("label[for=Error]").text("Insert a valid email");
}
requestCorreo.done(function (msg) {
alert(msg);
});
requestCorreo.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus + " " + jqXHR.responseText);
});
});
});
What is in the HTML that is returned? I'm going to bet that your method is throwing an exception, which is caught by ASP.NET, and an error page is returned rather than the JsonResult from your method.
Or it not, the content of the HTML would help shed more light on the issue.
As a side note, you don't seem to be checking null anywhere in your method - and you're assuming the MembershipUser will be found no matter what email address is passed (which may indeed be the source of your exception).
I have a problem with populating a Webgrid from an Ajax call.
I have followed the example as showed in the following thread: mvc3 populating bind webgrid from ajax however, that did not yield any results.
When I run the website, I always get the message: "Error: undefined".
when debugging the code, I am quite sure that the problem lies in the fact that the return PartialView is the problem, as my data object in the ajax success method does not get filled with data.
Here are the examples of my code:
Ajax call:
$.fn.getCardResult = function (leerling, kaart) {
$.ajax({
type: "GET",
url: '#Url.Action("GetResults","Kaarten")',
data: { leerlingID: leerling, cardID: kaart },
cache: false,
success: function (data) {
console.log(data);
if (!data.ok) {
window.alert(' error : ' + data.message);
}
else {
$('#card').html(data);
}
}
});
}
Partial View call:
<div class="card-content" id="card">
#{
if(Model.Kaart != null && Model.Kaart.Count > 0)
{
#Html.Partial("_Kaarten")
}
else
{
#: Er zijn geen kaarten beschikbaar.
}
}
</div>
Partial View:
#model List<ProjectCarrousel.Models.KaartenModel>
#{
var grid = new WebGrid(source: Model,ajaxUpdateContainerId: "card",
defaultSort: "Topicname");
grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column("Topicname", "Topic"),
grid.Column("Taskname", "Taken"),
grid.Column("Taskpoints", "Punten"),
grid.Column("Grades", "Resultaat"),
grid.Column("Date", "Datum"),
grid.Column("Teachercode", "Paraaf Docent")
)
);
}
Controller code:
public ActionResult GetResults(int leerlingID, string cardID)
{
try
{
int Ovnumber = leerlingID;
string CardId = cardID;
List<KaartenModel> kaartlijst = new List<KaartenModel>();
IEnumerable<topic> topics = _db.topic.Include("tasks.studenttotask").Where(i => i.CardID == CardId);
foreach (topic topic in topics)
{
foreach (tasks task in topic.tasks)
{
KaartenModel ka = new KaartenModel();
ka.Topicname = task.topic.Topicname;
ka.Taskname = task.Taskname;
ka.Taskpoints = task.Taskpoints;
ka.Ranks = task.Ranks;
ka.Date = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Date).SingleOrDefault();
ka.Grades = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Grades).SingleOrDefault();
ka.Teachercode = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Teachercode).SingleOrDefault();
kaartlijst.Add(ka);
}
}
KVM.Kaart = kaartlijst;
return PartialView("_Kaarten", KVM.Kaart);
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
If anyone could help it would be greatly appreciated.
UPDATE
After fiddling about a bit I found a solution that worked for me. Below is a snippet of an updated Ajax Call:
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
I am displaying multiple records on my ASP.NET MVC 4 view where each record has a checkbox. I want the user to be able to select multiple records (by checking checkboxes) and click Delete button in order to delete them. So far I can call the Delete Action method via jquery ajax but the problem is my action method does not seem to be accepting the passed array.
Here is my jquery code:
$(function () {
$.ajaxSetup({ cache: false });
$("#btnDelete").click(function () {
$("#ServicesForm").submit();
});
$("#ServicesForm").submit(function () {
var servicesCheckboxes = new Array();
$("input:checked").each(function () {
//console.log($(this).val()); //works fine
servicesCheckboxes.push($(this).val());
});
$.ajax({
url: this.action,
type: this.method,
data: servicesCheckboxes,
success: function (result) {
if (result.success) {
}
else {
}
}
});
return false;
});
});
and here is my action method:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
if (deleteservice != null)
{
//no hit
}
}
What am I missing?
Edit
I also tried console.log(servicesCheckboxes); before $.ajax() which outputs ["3", "4"] but still get null when I pass data as specified in answer below data: { deleteservice: servicesCheckboxes }. Even I tried data: [1,2] but still action method shows null for deleteservice in action method.
Just pass the array to your action:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: { deleteservice: servicesCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
Or, just use the serialize() jquery method to serialize all fields inside your form:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: $(this).serialize(),
success: function (result) {
if (result.success) {
}
else {
}
}
});
In your controller:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
bool deleted = false;
if (deleteservice != null)
{
// process delete
deleted = true;
}
return Json(new { success = deleted });
}
Finally got it working. "MVC detects what type of data it receive by contentType" as explained here so I made the following changes to $.ajax()
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
//data: { deleteservice: servicesCheckboxes }, // using the parameter name
data: JSON.stringify({ deleteservice: servicesCheckboxes }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});
I am trying to make an AJax call to a controller method the parameter is null no matter what I try. I have followed all the similar SO posts but to no avail. Sorry if the answer is there, I cant find it. The code I have is...
Ajax Call
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
type: 'POST',
dataType: 'json',
data: JSON.stringify({guid: sguid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Controller Method
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
List<DeviceSoftware> ldevice = new List<DeviceSoftware>();
Guid i = Guid.Parse(guid);
ReportMethods reportingMethods = new ReportMethods();
ldevice = reportingMethods.GetNonCompliantApplicationReport(CompanyId);
DeviceSoftware ds = ldevice.Find(x => x.Device.Guid == i);
List<DeviceApplication> da = new List<DeviceApplication>();
if (ds != null)
{
da = ds.DeviceApplications;
}
return Json(da, JsonRequestBehavior.AllowGet);
}
The method is being hit its just guid is alway null. sguid does hold the data I am trying to pass.
Can someone tell me what I am missing?
Against everything I read I changed
data: JSON.stringify({guid: sguid}),
To
data: {guid: sguid},
Now working.
Fred,
You need to make GetBlacklistedSoftwareItems a post method....
try this...
[HttpPost]
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
Small changes needs to be done.
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
contentType: "application/json; charset=utf-8" ,//This is very important
type: 'POST',
dataType: 'json',
Data: JSON. stringify ({guild: squid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Add the contentType: "application/json; charset=utf-8" , to the $.Ajax Call.
:)