AJAX POST Not Returning - c#

In my C# MVC4 application, I perform the following AJAX Post:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('.rowselection').click(function (e) {
var tdata = $('#form1').serialize();
$.ajax({
type: "POST",
data: tdata,
url: "/Home/PartialAverage",
success: function (result) { success(result); }
});
});
function success(result) {
$("#Display_Average").html(result);
}
});
</script>
While running the application on localhost and performing testing, never immediately, but almost always after a considerable amount of time passes, which I click the checkboxes which initiate the POST, the POSTS fail to return in a timely manner or even at all in some instances. This isn't acceptable because the post refreshes a partial view that displays quickly needed data.
What could be causing this, is it something I can prevent, and is it something I can expect to see once I post to production?
Here is my ActionResult:
[HttpPost]
public ActionResult PartialAverage(ChViewModel model, FormCollection myFcollection)
{
HomeModel C = new HomeModel();
System.Data.DataTable myDT = new System.Data.DataTable();
myDT = (DataTable)Session["DT"];
ChViewModel D = new ChViewModel();
D = model;
D = C.AverageCalculation(myDT, myFcollection, D);
ViewData["SampleTypes"] = C.SampleTypeList;
Session["Counter"] = 0;
return PartialView(D);
}

Related

Ajax Posting twice ASP NET CORE MVC

Controller
[HttpPost]
public IActionResult Index(string mainFin, string actNumber, int actTypeId)
{
int userId = Int16.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
Act act = new Act()
{
ActTypeId = actTypeId,
CreateDate = DateTime.Now,
ApproveDate = null,
UserId = userId,
StatusId = 1,
};
_unitOfWork.ActRepository.Add(act);
_notyf.Success("Arayış əlavə edilid !");
_unitOfWork.Complete();
return RedirectToAction("Marriage");
}
AJAX
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
},
error: function () {
console.log("------");
}
});
e.preventDefault();
$("#questForm1").submit();
});
});
Problem : When I click submit button data inserts twice to database (AJAX makes 2 request at same time )
If you want to submit the form via AJAX then you need to remove the last line of the click event handler.
$("#questForm1").submit();
This line is submitting the form and essentially negating the e.preventDefault() above.
You are submitting your data twice: at first using ajax and after that using using the form submit.
You have to remove one of them, I would guess the form submit.
Also, since ajax is called async, if you want to do something after ajax has been called and returned successfully, you have to put the code in success section.
So the code should look like:
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
e.preventDefault();
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
// do your thing here, once the ajax requst has returned successfully
},
error: function () {
console.log("------");
}
});
// NOTICE: form submit removed
});
});

MVC drop down list onchange pass the selected value to the function in the controller and execute it

i am a new in using MVC3 Razor syntax and i have a view that containing a dropdownlist and i want when the user change the value of it , a function in the controller that take selected value as a parameter will be executed automatically.
this is the code that i wrote in the view and i have a compilation error in that line at runtime:
#Html.DropDownList("DONOR_BLOOD_GROUPE_ID", "--Select--", new {onchange="FilterdIndex(this.value)"})
"DONOR_BLOOD_GROUPE_ID" is in the viewBag and this is the function in the controller that i want to call .
public ViewResult FilterdIndex(int id)
{
var donor = db.DONOR.Include(d => d.BLOOD_GROUP);
var DONOR_BLOOD_GROUPE_ID = from BG in db.BLOOD_GROUP
select new
{
BG.GROUP_ID,BG.GROUP_NAME,
Checked=(BG.GROUP_ID==id)
};
ViewBag.DONOR_BLOOD_GROUPE_ID = DONOR_BLOOD_GROUPE_ID;
return View(donor.ToList());
}
this is javascript code it executes the controller function correctly but i don't know why after returning to the view i have the error msg in this line :
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
and this is the whole function:
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
if ($("#DONOR_BLOOD_GROUPE_ID").val() != "Select") {
var DONOR_BLOOD_GROUPE = {};
DONOR_BLOOD_GROUPE.url = '#Url.Action("FilterdIndex", "DONOR")';
DONOR_BLOOD_GROUPE.type = "POST";
DONOR_BLOOD_GROUPE.data = JSON.stringify({ id: $("#DONOR_BLOOD_GROUPE_ID").val() });
DONOR_BLOOD_GROUPE.datatype = "html";
DONOR_BLOOD_GROUPE.contentType = "application/json";
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
$.ajax(DONOR_BLOOD_GROUPE);
}
});
});
</script>
and this is the line that causes the exception in "DONOR[dynamic]" file
<select AutoPostBack="True" id="DONOR_BLOOD_GROUPE_ID" name="DONOR_BLOOD_GROUPE_ID" onchange="FilterdIndex(this.value)"><option value="">--Select--</option>
I assume you come from a WebForms background where this sort of thing happens all the time with 'Events' this sadly is not how MVC works.
To do what you are trying to do, you will need to create a jquery method for the onchange event of that drop down, then do an async post to your controller.
Have a look at this tutorial which should point you in the right direction
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Hi Asmaa Rashad you can try using this way and your action Method which you are calling using Ajax must be of type JsonResult.
<script type="text/javascript">
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("FilterdIndex", "DONOR")',
dataType: 'json',
data: { id: $("#DONOR_BLOOD_GROUPE_ID").val() },
success: function (data) {
},
error: function (ex) {
alert('Failed to retrieve + ex);
}
});
return false;
})
});
</script>
For reference you can check this blog creating-simple-cascading-dropdownlist-in-mvc-4-using-razor

AJAX HTTP Method GET Goes To Server Only Once

When I make ajax request to the server with breakpoint in the action method it stops on this breakpoint only the first time. After clicking for second, third etc. it goes but never stops on this breakpoint. When I change the method from GET to POST it stops every time. What is the reason for this behaviour ?
CLIENT SIDE:
$(function () {
setListAction();
});
function setListAction() {
$("li.list").on("click", function () {
alert("active");
var id = $(this).attr("file-id");
$.ajax({
type: "GET",
url: "TechAcc/ManageFile/" + id,
beforeSend: function myfunction() {
$("#loading").css("display", "block");
$("#fade").css("display", "block");
},
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}
});
});
}
SERVER SIDE:
[HttpGet]
public ActionResult ManageFile(int id = 0)
{
FileModel model = null;
if (id != 0)
model = new FileModel() { File = _repository.GetFileBy(id), GetAllFiles = _repository.GetAllFiles() };
else if (Session["Model"] != null)
model = (FileModel)Session["Model"];
else
model = new FileModel() { GetAllFiles = _repository.GetAllFiles() };
return View(model);
}
if your div with id "content" has list, it will not work.
<div id="content">
if your list is here, it won't work.
...
<li class="list">...</li>
...
</div>
if your design is like that, you need to bind click event after you replace your HTML response. i.e.,
success: function (data) {
var content = $(data).find("div#content");
$("div#content").html(content.html());
//adding code here.
$("div#content").find("li.list").on("click", function() {
//same above click code should come here.
//Note: this newly added code block should not come here in click.
});
$("#loading").css("display", "none");
$("#fade").css("display", "none");
}

Using Ajax to trigger an Action Result c#

Using the following script:
$(document).ready(function () {
$('#submit').click(function () {
var companyId = $('#companyCoid').val();
var erpKey = $('#erpKey').val();
if (companyId == "" || erpKey == "") {
alert("You have not entered enough information");
} else {
$.ajax({
type:post,
url: '#Url.Action("ErpDocument")',
data: {
coid: companyId,
documentKey: erpKey
}
});
}
});
});
I am trying to trigger this action result which would navigate to a new view:
[HttpPost]
public ActionResult ErpDocument(string coid, string documentKey)
{
var cview = new ConnectorViewModel();
Stuff and things here....
return View(cview);
}
I am getting the information from a form above and the check for blank fields works just fine, however, the function in my controller is never hit.
EDIT: Reason it wasn't hitting the ActionResult was I had post and not "POST", this now hits my method but does not display my new view.
I think the default contenttype is xml. you may need to add this
contenttype: "application/json; charset=utf-8"
. I think that's what I've had to do before. Although unlikely, you may need to add a datatype as well.
https://api.jquery.com/jQuery.ajax/

Autocomplete: display results with json data

I am trying to build an autocomplete, but I have troubles patching along the parts.
First, my view include this field:
<p>#Html.TextBoxFor(_item => _item.mCardName, Model.mCardName, new { #class = "cardText", id = "card_name"} ) </p>
Very simple. Next, the javascript call:
<script type="text/javascript">
$(function() {
$('#card_name').autocomplete({
minlength: 5,
source: "#Url.Action("ListNames", "Card")",
select: function (event, ui) {
$('#card_name').text(ui.item.value);
},
});
});
</script>
Which calls this method:
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
If i insert the "Power" word, the JSON data is posted back like this:
{"ContentEncoding":null,"ContentType":null,"Data":[{"CARD_NAME":"Power Armor"},{"CARD_NAME":"Power Armor (Foil)"},{"CARD_NAME":"Power Artifact"},{"CARD_NAME":"Power Conduit"},{"CARD_NAME":"Power Conduit (Foil)"},{"CARD_NAME":"Power Leak"},{"CARD_NAME":"Power Matrix"},{"CARD_NAME":"Power Matrix (Foil)"},{"CARD_NAME":"Power of Fire"},{"CARD_NAME":"Power of Fire (Foil)"},{"CARD_NAME":"Power Sink"},{"CARD_NAME":"Power Sink (Foil)"},{"CARD_NAME":"Power Surge"},{"CARD_NAME":"Power Taint"},{"CARD_NAME":"Powerleech"},{"CARD_NAME":"Powerstone Minefield"},{"CARD_NAME":"Powerstone Minefield (Foil)"}],"JsonRequestBehavior":0,"MaxJsonLength":null,"RecursionLimit":null}
For reference purpose, here are two of the scripts that run:
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
However nothing is displayed. I would have liked to see the results displayed like a normal autocomplete would do. Can anyone help me out making things work?
EDIT
I have been working on this for a while. I have posted up there the new javascript, controller method and results obtained. But the thing still does not work and I would appreciate any help.
for autocompletes, i use the javascriptserializer class. the code goes something like this.
My.Response.ContentType = "application/json"
Dim serializer As JavaScriptSerializer = New JavaScriptSerializer
Dim dt As DataTable = GetDataTable("proc_name", My.Request.QueryString("term"))
Dim orgArray As ArrayList = New ArrayList
For Each row As DataRow In dt.Rows
Dim thisorg As New thisOrg
thisorg.id = row("organization_child_id")
thisorg.value = row("organization_name")
orgArray.Add(thisorg)
Next
My.Response.Write(serializer.Serialize(orgArray))
Public Class thisOrg
Public id As Integer
Public value As String
End Class
basically just takes a datatable, adds a series of objects to the array, then serializes it.
Finally! After taking a break, I got my answer.
See this?
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
As it happens, I was building a Json object OF another Json object. So that's why the data was not passed properly.
I've rebuilt the method, made it work, and refined it like this:
public JsonResult ListCardNames(string term)
{
using (BlueBerry_MagicEntities db = new BlueBerry_MagicEntities())
{
db.Database.Connection.Open();
var results = from cards in db.V_ITEM_LISTING
where cards.CARD_NAME.ToLower().StartsWith(term.ToLower())
select cards.CARD_NAME + " - " + cards.CARD_SET_NAME;
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return result;
}
And my javascript action:
<script type="text/javascript">
$(function() {
$('#searchBox').autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("ListCardNames")",
type: "GET",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item, value1: item };
}));
}
});
},
select:
function(event, ui) {
$('#searchBox').val(ui.item);
$('#cardNameValue').val(ui.item);
return false;
},
minLength: 4
});
});
</script>
And now everything works like a charm.

Categories

Resources