Ajax PostBack: Read data from Controller - ajax

How do I read the data from my controller in my ajax postback?
I have a Razor form
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
And I catch the Submit action in JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#createDocumentForm").submit(
function () {
showWaitMode();
$.ajax({
data: ("#createDocumentForm").serialize,
success: (e) => {
console.log(e);
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
});
</script>
In my controller I hit this method:
public ActionResult CreateDocument(NotatFletModel model)
{
var reuslt = new
{
Staus = true,
GoDocumentId = model.ContactId.ToString(),
ErrorMessage = model.DocumentKindId,
};
return Json(reuslt);
}
But in my Ajax success function I would like to get the data from my contorller. I expected it to be in my parameter e but it's not
So in short: How do I do an Ajax post and read the data posted back from the controller

Checkout my code for Form Post using ajax
Html :
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
Jquery :
$("#createDocumentForm").submit(
function (e) {
showWaitMode();
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
url: url,
type: 'POST',
data: form.serialize(), // serializes the form's elements.
success: function (data) {
console.log(data); // show response
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
Controller :
//You can Use FormCollection also to get data
//public ActionResult CreateDocument(FormCollection fc) {
[HttpPost]
public ActionResult CreateDocument(NotatFletModel model) {
//your logic
return Json(model, JsonRequestBehavior.AllowGet);
}

Related

How to display update content after posting data by ajax in asp.net core entity framework core

I want to display update content after posting data by jquery ajax. I tried it but not display data.
here is my code...
jquery ajax
$(document).ready(function () {
$('#paid').click(function () {
var pid = $('#pid').val();
var amt = $('#amt').val();
var payType = $('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
}
});
});
})
controller
[HttpPost]
public async Task<IActionResult> AddPaidBalance(PatientBilling patientBilling)
{
if (ModelState.IsValid)
{
_db.PatientBilling.Add(patientBilling);
await _db.SaveChangesAsync();
//return RedirectToAction("Details", "Registration", new { area = "Reception", id = patientBilling.PatientId });
//return RedirectToAction("Details", "Registration", new { patientBilling.PatientId});
}
return View();
}
help me out from this issue.
Based on your code, you make ajax request to post data of PatientBilling to action method. To display new-added PatientBilling information on Details page after the request completes successfully, you can do redirection in success callback function, like below.
<script>
$(document).ready(function () {
$('#paid').click(function () {
var pid = 1;//$('#pid').val();
var amt = "amt";//$('#amt').val();
var payType = "type1";//$('#payType').val();
$.ajax({
type: "POST",
url: "/Reception/Registration/AddPaidBalance",
data: { PatientId: pid, PaidAmt: amt, PaymentType: payType },
success: function (data) {
window.location.href = "#Url.Action("Details", "Registration", new { Area = "Reception"})" + "?patientId=" + pid;
}
});
});
})
</script>
Details action
public IActionResult Details(int patientId)
{
// code logic here
// get details of PatientBilling based on received patientId
// ...
return View(model);
}

Value cannot be null. Parameter name entity

I want to delete using Ajax. When I press the Delete button, an exception occurs:
Value cannot be null. Parameter name entity.
The controller code is as follows:
public ActionResult DeleteCar(int? Id)
{
var cardetail = car.Cars.Find(Id);
return View(cardetail);
}
public ActionResult DeleteConfirmed(int? Carid)
{
Car cardetail = car.Cars.Find(Carid);
car.Cars.Remove(cardetail);
car.SaveChanges();
return Content("Success");
}
The Ajax code of delete as follows.
$(document).on('click', '.deleteStd', function () {
// alert();
var Carid = $(this).attr('id');
$.ajax({
type: "post",
url: "/Home/DeleteConfirmed?Carid=" + Carid,
ajaxasync: true,
success: function () {
alert("Record delete successfully");
location.reload();
},
error: function (data) {
alert(data.x);
}
});
});

asp.net mvc index action is called automatically after ajax

I have an action that creates a record in the database:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Description")] SampleViewModel sampleVM)
{
try
{
_service.Add(sampleVM);
this.ShowMessage(new ToastMessage(ToastType.Success, "Record Added", ToastrDisplayType.TopLeft));
}
catch (Exception ex)
{
this.ShowMessage(new ToastMessage(ToastType.Error, ex.Message, ToastrDisplayType.TopLeft));
return Json("failed");
}
return Json("success");
}
this Action is called by AJAX:
$().ready(function () {
$("#btnSave").click(function () {
var serviceURL = '';
var sample = {
"Id": $('#hdnId').val(),
"Name": $("#txtName").val(),
"Description": $("#txtDescription").val(),
};
if (save_method == 'add') {
serviceURL = '#Url.Action("Create", "Samples")';
}
else if (save_method == 'edit') {
serviceURL = '#Url.Action("Edit", "Samples")';
}
$.ajax({
type: "POST",
url: serviceURL,
data: addRequestVerificationToken(sample),
success: function (data, textStatus, jqXHR) {
handleAjaxMessages();
},
});
});
});
The problem is that the Index Action is called automatically after the Create Action:
[HttpGet]
public ActionResult Index()
{
return View();
}
Fiddler snapshot
The Toast message is not displayed because the Index Action is called, How can I call the Create Action only (without calling the Index Action)?
So your "#btnSave" is a <button type="submit" /> button. The browser will do the following in order:
Invoke your own click handler, that you have shown in your code.
Post the <form> that your button is in to the server and reload the page with the answer that it gives.
You have two options: either you remove the form and have a regular <button> (without type="submit"), or you modify your click handler a little:
$("#btnSave").click(function (event) {
event.preventDefault(); // notice this line
var serviceURL = '';

MVC4 Ajax- Pass complete model to controller

I have my AJAX call
$.ajax({
type: 'post',
url: "/Store/LoadStoreIndex",
data: , //Entire Model Here!!
dataType: "text",
success: function (result) {
$('#Postback').html(result);
}
});
I need to send my entire model back to the controller, but after much searching can't find anything ... Can somebody show me what I need to be doing?
Controller Get Action
public ActionResult Index(YourModel model)
{
YourModel model = new YourModel();
return View(model);
}
View
#model YourModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.TextBoxFor(x => x.EmailAddress)
#Html.TextBoxFor(x => x.Name)
...
}
Script
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
// you can post your model with this line
data: $(this).serialize(),
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
},
error: function () {
}
});
}
return false;
});
});
Controller Post Action
[HttpPost]
public ActionResult Index(YourModel model)
{
return View();
}

Jquery dialog & Ajax posting wrong(?) result in ASP.NET MVC3 (razor)

What i want to do:
at page load to automatically pop up a jquery dialog fill in some data, post that to an action and close the dialog (regardless if the action succeeds or not).
in the View in which the pop up should occur i have the following:
<script type="text/javascript">
$(function () {
$('#PopUpDialog').dialog(
{
modal: true,
open: function ()
{
$(this).load('#Url.Action("Subscription", "PopUp")');
},
closeOnEscape: false
}
);
$('.ui-dialog-titlebar').hide();
$('#closeId').live('click',function () {
$('#PopUpDialog').dialog('close');
return false;
}
);
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize()
})
return fase;
}
);
});
</script>
the Subscription view has the following:
#using (Html.BeginForm( new { id = "SubscriptionForm" }))
{
#Html.ActionLink(Deals.Views.PopUp.SubscriptionResources.AlreadySubscribed, "", null, new { id = "closeId" })
<br />
<br />
#Deals.Views.PopUp.SubscriptionResources.FillEmail
#Html.TextBoxFor(m => Model.Email)
<input type="submit" id="subscribeId" value="#Deals.Views.PopUp.SubscriptionResources.IWantToSubscribe" />
<br />
}
which works fine.
The POST action is defined as follows:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Subscription(FormCollection formValues)
//public void Subscription(FormCollection formValues)
{
Deals.ViewModels.PopUpSubscriptionVM VM = new ViewModels.PopUpSubscriptionVM();
TryUpdateModel(VM);
if (!String.IsNullOrEmpty(VM.Email))
{
//do the update to the dbms
}
return Json(new { success = true });
}
The problem is that after posting back i get an empty screen with the success message, which i don't want!
What am i doing wrong?
You can handle the success and error callbacks:
$('#SubscriptionForm').submit(function () {
$("#PopUpDialog").dialog("close");
$.ajax({
url: encodeURI('#Url.Action("Subscription", "PopUp")' ),
type: this.method,
data: $(this).serialize(),
success: function (result) {
//Do Whatever you want to do here
},
error: function (x, e) {
//Do Whatever you want to do here
}
})
return fase;
}
To see what i am doing wrong i set up a small project (ASP.NET MVC 3) with the following ingredients:
<script type="text/javascript">
$(function () {
// Does not cache the ajax requests to the controller e.g. IE7/9 is doing that...
$.ajaxSetup({ cache: false });
var $loading = $('<img src="#Url.Content("~/images/ajax-Loader.gif")" alt="loading" class="ui-loading-icon">');
var $url = '#Url.Action("Subscription", "PopUp")';
var $title = 'Some title';
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
, closeOnEscape: false
, title: $title
, width: 500
, modal: true
, minHeight: 200
, show: 'fade'
, hide: 'fade'
});
$dialog.dialog("option", "buttons", {
"Cancel": function () {
$(this).dialog("close");
$(this).empty();
},
"Submit": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#SubscriptionForm").serialize(),
success: function (response) {
//$(target).html(response);
dlg.dialog('close');
dlg.empty();
});
}
});
$dialog.dialog('open');
})
</script>
The controllers' actions:
public ActionResult Subscription()
{
Thread.Sleep(2000); //just for testing
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
return View(VM);
}
//POST
[AcceptVerbs(HttpVerbs.Post)]
//[OutputCache(CacheProfile = "ZeroCacheProfile")]
public ActionResult Subscription(FormCollection formValues)
{
TestModalAjax.ViewModels.PopUpVM VM = new ViewModels.PopUpVM();
TryUpdateModel(VM);
return Json(new { success = true });
}
...and the according View:
#model TestModalAjax.ViewModels.PopUpVM
#{
Layout = null;
ViewBag.Title = "Subscription";
}
<h2>Subscription</h2>
#* ----- NOTICE THE FOLLOWING!!! WITHOUT THIS DATA GETS NOT POSTED BACK!!!! ---- *#
#using (Html.BeginForm("Subscription","PopUp",FormMethod.Post, new { id="SubscriptionForm"}))
{
<h1> Give me your name</h1>
#Html.TextBoxFor(M => Model.Name)
}
...so it seems everything works as expected!

Resources