Issue with TypeScript and controller - c#

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.

Related

Asp.net core MVC and JQuery submit

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")

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

Error while binding through ajax call

I am doing ajax call in Asp.Net MVC with this code
$.ajax({
type: "GET",
url: '#Url.Action("GetAllFacts", "Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[0].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[0].Content + "'</div></div></div></div>");
//$('#AllFacts_Data').append("<div class='col-md-4'><div class='text-center facts-data-box bg_facts_grey'><div class='inner-div'><span><img src=" + data[1].ImageUrl + " class='image_top '></span><div class='text-center twit-all-content facts-content_blu'>'" + data[1].Content + "'</div></div></div></div>");
},
error: function () {
alert("Error");
}
});
This hits to my Get Method GetAllFacts() with following codes
[HttpGet]
public JsonResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(allData_Facts, JsonRequestBehavior.AllowGet);
}
}
catch (Exception)
{
}
return Json("false", JsonRequestBehavior.AllowGet);
}
This is my code which returns list with 2 data properly, but after that it is not going to success method it alerts error as per Ajax error function.
Where I am wrong?
Try by
Remove assembly reference System.Web.Mvc out of your project.
Use nuget to install System.Web.Mvc for you project.
Verify Web.config to make sure it have System.Web.Mvc assembly.
Run to check.
Good luck!
ajax:
$.ajax({
type: "GET",
url: '/Home/GetAllFacts',
dataType: "json",
success: function (data) {
if (data.success) {
// connect to server successful and everything's ok
// access to server returned data: data.alldata
} else {
// connect to server successful but something went wrong
alert(data.ex); // throw exception message
}
},
error: function () {
// connect to server failure
}
});
controller:
[HttpGet]
public ActionResult GetAllFacts()
{
try
{
using (var context = new DbDemo())
{
var allData_Facts = context.Objblog.Take(2).ToList();
return Json(new { success = true, alldata = allData_Facts }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception e)
{
return Json(new { success = false, ex = e.Message }, JsonRequestBehavior.AllowGet);
}
}

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.

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