Asp.net core MVC and JQuery submit - c#

I have this code(JQuery) in my View:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
var link = '#Url.Action("Action", "Controller")';
var args = {
MyFVal: MyFVal.val(),
MySVal: MySVal.val()
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.acces);
if (data.acces) {
AllEnable();
form.submit();
}
else {
alert(data.erromessage);
}
},
error: function () {
alert("Error. Kontaktujte správce.");
}
});
});
When I gets submitted then I have this if in my save action.
if (Request.Form.ContainsKey("Insert"))
{
// do code that is supposed to run
}
else if (Request.Form.ContainsKey("Edit"))
{
// do another code
}
My problem is that because I submitted form by JQuery this if and elseif never gets executed.
Thanks for any help!

You might want to pass value for your requirements in Action condition. See operationType sample parameter
var obj = {
UniqueId: modelUniqueId.val(),
Name: modelName.val(),
operationType: $("[name=operationType]").val()
};
$.ajax({
type: "POST",
url: '/hrms/Class/Index',
data: obj,
success: function (result) {
if (result.success == true) {
createAndProcessPageAlert("success", result.message);
}
else {
createAndProcessPageAlert("error", result.message);
}
And in your Controller \ Action
[HttpPost]
public JsonResult Index(string operationType, ClassModel model)
{
var result = new HttpResponseModel<ClassModel>();
var user = Request.GetUserProfile();
if (operationType == "add")

Related

Ajax Jquery not return the URL after using ActionLink in MVC

I got a scenario:
Here's my ActionResult when ActionLink was Clicked
public PartialViewResult ViewHit(string id, string recordid,string statusSelect,string statusHitSelect)
{
//some code here....
}
The ActionLink where to post after the Button was clicked:
public ActionResult SaveUpdate(String statusSelect, string statusHitSelect)
{
return PartialView("ViewHitList");
}
Here's the button:
<input type="button" value="Save" id="savehit"/>
and Here's my Ajax:
$("#savehit").on('click', function () {
//alert("Button was click!");
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
//url: "SelectUpdate?statusSelect=" + statusSelect + '&statusHitSelect=' + statusHitSelect,
url: "SaveUpdate",
data: "{'statusSelect':'" + statusSelect + "','statusHitSelect':'" + statusHitSelect + "'}",
//data:null,
success: function (response) {
if (response != null && response.success) {
//InformationMessageSuccess(response.responseText);
alert("success");
} else {
// DoSomethingElse()
//InformationMessageFailed(response.responseText);
alert("not success");
}
},
});
});
The problem is, when i hit the save button using debug mode the ActionResult called was the ViewHit instead of SaveUpdate.
I am wondering why is it happen?
Any great idea is highly appreciated.
You can try to avoid default action of the event by using event.preventDefault()
$("#savehit").on('click', function (event) {
event.preventDefault();
//alert("Button was click!");
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
//url: "SelectUpdate?statusSelect=" + statusSelect + '&statusHitSelect=' + statusHitSelect,
url: "#Url.Action("SaveUpdate", "Home")",
data: "{'statusSelect':'" + statusSelect + "','statusHitSelect':'" + statusHitSelect + "'}",
//data:null,
success: function (response) {
if (response != null && response.success) {
//InformationMessageSuccess(response.responseText);
alert("success");
} else {
// DoSomethingElse()
//InformationMessageFailed(response.responseText);
alert("not success");
}
}
});
});
Add the [HttpPost] attribute to the SaveUpdate action
In the ajax, change the URL to url: "ControllerName/SaveUpdate"
Since you are expecting a boolean result (JSON) back to your page as the ajax response, simply return a jsonResult (true/false)
SaveUpdate is not post type please add attribute [HttpPost] at the top of the controller method like
[HttpPost]
public ActionResult SaveUpdate(String statusSelect, string statusHitSelect)
{
return PartialView("ViewHitList");
}
I have changed the ajax call like bellow and it the SaveUpdate method. Bellow is the ajax call.
$(document).ready(function () {
$("#savehit").on('click', function () {
var statusSelectData="statusSelect";
var statusHitSelectData="statusHitSelect";
var postData = {
statusSelect: statusSelectData,
statusHitSelect: statusHitSelectData
}
//alert("Button was click!");
$.ajax({
type: "POST",
url: "/Home/SaveUpdate",
data: postData,
//data:null,
success: function (response) {
if (response != null && response.success) {
//InformationMessageSuccess(response.responseText);
alert("success");
} else {
// DoSomethingElse()
//InformationMessageFailed(response.responseText);
alert("not success");
}
},
});
});
});

MVC and JQuery Load parameter List

I have a JQuery function that load some data from C# and update information on my view.
I must to load a large dataset and all works fine, but for some reason i must to load a dynamic list and elaborate its from JQuery.
The list is "listCasistiche" and when i load it from MVC the JQuery function goes in error.
How can i take this list?
The JQuery function is this:
var data = $('#jqxgrid').jqxGrid('getrowdata', rowindex);
var uf = new FormData();
uf.append("id", data.Id);
var url = "/Clienti/LoadSelezionato";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
// The function go in error
},
success: function (result) {
if (result != "error") {
result.listCasistiche.forEach(function (entry) {
alert(entry.IdCasistica);
});
ricaricaNeri();
$('#OwnLead').val(result.ownerLead);
$('#dataLead').datepicker('setDate', result.dataLead);
}
}
});
The MVC LoadSelezionato function is this. All other parameters are loaded well:
[HttpPost]
public ActionResult LoadSelezionato(FormCollection form)
{
int id = Convert.ToInt32(form["id"]);
try
{
Cliente clienteLead = conc.Clientes.FirstOrDefault(x => x.Id == id);
if (clienteLead != null)
{
var elemento = new
{
ownerLead = clienteLead.OwnerLead,
dataLead = clienteLead.DataLead,
listCasistiche = conc.CasisticheClientes.Where(x => x.IdCliente == id).ToList()
};
return Json(elemento, JsonRequestBehavior.AllowGet);
}
else
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
Thanks to all

Transforming List into a Json C#

I'm trying to convert a List into a Json to send it to an Ajax Request, but when I recover only one register from the Database it works, but if I have more then one, the ajax returns an error.
Below is my code:
public ActionResult RecuperaLocalidadesPorUsuario(int usuarioId)
{
BpUsuario m = new BpUsuario();
IList<Localidade> states = m.ObterPorId(usuarioId).Localidades.ToList();
states.Add(m.ObterPorId(usuarioId).UsuaAreaPadrao);
var result = (from s in states.Where(x => x != null).Distinct().ToList()
select new { id = s.LocaCodigo, name = s.LocaNome}
).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here is the Ajax call
$.ajax({
cache: false,
type: "GET",
url: "#(Url.Action("RecuperaLocalidadesPorUsuario", "Usuario"))",
data: { "usuarioId": selectedItem },
contentType: 'json',
success: function (data) {
alert("entrou no success");
if (data.length == 0) {
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("O Usuário não tem localidades cadastradas"));
ddlLocalidades.attr("disabled", true);
} else {
ddlLocalidades.attr("disabled", false);
ddlLocalidades.find('option').remove();
ddlLocalidades.append($('<option></option>').val("").html("Todas"));
$.each(data, function (id, option) {
if (option.id == '#Request.Cookies.Get("UserAreaPadrao").Value') {
ddlLocalidades.append($('<option selected></option>').val(option.name).html(option.name));
} else {
ddlLocalidades.append($('<option></option>').val(option.name).html(option.name));
}
});
}
$('#ddlLocalidades').multiselect('rebuild');
},
error: function (data) {
alert("entrou no error");
}
});
I tried many links here at stackoverflow , but without any success, and I'm really stuck into this problem.

Issue with TypeScript and controller

So I'm converting a site form VB to C# and using TypeScript in the process. I have it successfully passing the data to the controller, however the controller post back to the same page instead to the next page.
Here's the TypeScript (full module here)
function formSubmission(submitId, submitUrl, formData, validation) {
if (!submitId || hasSubmit)
return false;
if (validation) {
if (!$("#empApp form").validate().form())
return false;
hasSubmit = true;
}
hasSubmit = true;
// add load status functionality
$(".modal").modal("show");
$.ajax({
type: "POST",
url: submitUrl,
data: formData,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
window.location.href = "/employment/application/references";
},
error: function (xhr, ajaxOptions, error) {
$(".modal-body").html("<h3>" + status + "<small>" + error + "</small></h3>");
setTimeout(function () {
$(".modal").modal("hide");
}, 100);
window.location.href = "/employment/application/work-experience";
}
});
}
Here's the Controller (full here)
[HttpPost, Route("Work-Experience")]
public ActionResult WorkExperience(List<EmploymentApplicationWorkExperience> appExperience)
{
EmploymentApplication empAppSession = getApplication();
if (!HasSession()) { return InvalidAppSession(); };
SetupViewBag();
if (!empAppSession.Steps.HasFlag(EmploymentApplication.ApplicationStepTypes.EducationSkills))
{
return PartialView(GetApplicationStepError());
}
if (ModelState.IsValid)
{
if (appExperience != null)
{
empAppSession.ApplicationWorkEperiences = appExperience;
// empAppSession.Application.empApWorkExperiences = (ICollection<empApWorkExperience>)appExperience;
empAppSession.StepCompleted(EmploymentApplication.ApplicationStepTypes.Workexperiences);
updateApplicationStep(empAppSession.Steps);
updateApplicationWorkExpriences(empAppSession.ApplicationWorkEperiences);
updateApplication(empAppSession.Application);
return RedirectToAction("References");
}
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
else
{
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
}
Used a unnecessary filter on Controller that if not valid, would continue to return the current page. Once removed, page continued with out post back issue.

asp.net MVC pass server value to hidden field

From my OnePageCheckout.cshtml View i call ajax controller
#Html.Hidden("StepContent", (string)ViewBag.newAddress) #* never work *#
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: this.nextStep, // still stay in the same page
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel)
},
goto_section = "confirm_order"
});
}
How can I update the status of the hidden input with a value from the controller?
UPDATE 2:
var Billing = {
form: false,
saveUrl: false,
init: function (form, saveUrl) {
this.form = form;
this.saveUrl = saveUrl;
},
save: function () {
if (Checkout.loadWaiting != false) return;
Checkout.setLoadWaiting('billing');
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
this.nextStep; << nextStep won't be called !! but it works for success: this.nextStep
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
},
resetLoadWaiting: function () {
Checkout.setLoadWaiting(false);
},
nextStep: function (response) {
alert('aa');
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
$('#StepContent').val($("#billing-address-select").find('option:selected').text());
Checkout.setStepResponse(response);
}
};
Change status in JS after ajax call,
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
$("#StepContent").val(data.status);
this.nextStep;
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
and controller pass status in JSON
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel),
},
status = "abc",
goto_section = "confirm_order"
});
}

Categories

Resources