AJAX HTTP Method GET Goes To Server Only Once - c#

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

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

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/

How to get the data from json to MVC4 c#?

I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).

Passing a parameter from JavaScript to a controller

I am trying to pass a string value to a create item dialog, and am not sure on how to do it.
This is the code in my view:
JavaScript:
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}
View:
<td>#route</td>
<td>
Add
</td>
Controller:
public ActionResult Create(string routeName = "")
{
PopulateRouteInfoViewBag();
var newRoute = new RouteInformation();
newRoute.Name = routeName;
return View(newRoute);
}
I'm trying to take the value in #route and pass it over to the Create controller to have my dialog pop up with the passed in string value.
Use the ActionLink html helper method and pass the route variable like this.
#{
string route="somevaluehere";
}
#Html.ActionLink("Add","Create","YourControllerName",
new { routeName=route},new {#id="addLnk"})
Now handle the click event
$(function(){
$("#addLnk").click(function(e){
e.preventDefault(); //prevent normal link click behaviour
var _this=$(this);
//do your ajax call now
$.ajax({
url: _this.attr("href"),
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = 'someValidUrlHere'
else
$.facybox(data);
}
});
});
});
Also, You may consider building the path to the new page(action method) and return that as part of your JSON result and let the client read it from the JSON.
instead of appending the route variable value to the querystring, you may consider it as the part of message body.
There are two options. 1, use Url.Action("controllerName", "actionName", new {routeName = "your route name here"}) or 2, use the data property of the object passed into $.ajax.
For 2 your javascript would look something like
function newRoute() {
$.ajax({
url: '#Url.Action("Create")',
data: {
route: "your data here"
}
success: function (data) {
if (data == "success") //successfully created the new route
window.location.href = '#Url.RouteUrl(ViewContext.RouteData.Values)'
else
$.facybox(data); // there are validation errors, show the dialog w/ the errors
}
});
}

Categories

Resources