this is PartialView Code:
#*This PartialView will return by return PartialView()*#
<script>
alert("OK")
</script>
<h1>test</h1>
this is IActionResult Code:
[HttpPost]
public IActionResult Test()
{
return PartialView("Test");
}
** Call ActionResult**
let Test = () => {
$.ajax({
method: 'POST',
url: "/Home/Test",
success: function(data, status, xhr) {
let itm = document.getElementById("MainPage");
itm.innerHTML = data;
}
}).done(function(res) {
}).fail(function(data, status, xhr) {
});
}
</script>
after call javascript Test() function,partialview return successfully but alert("OK") not work
Related
I got error like "Failed to load resource: the server responded with a status of 400 ()" when i'm trying to run function ajax in javascript. What to do? Please, help me!
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="container">
<p id="scanned"></p>
</div>
<script type="text/javascript">
function Q(el) {
if (typeof el === "string") {
var els = document.querySelectorAll(el);
return typeof els === "undefined" ? undefined : els.length > 1 ? els : els[0];
}
return el;
}
var txt = "innerText" in HTMLElement.prototype ? "innerText" : "textContent";
var scannedQR = Q("#scanned");
var args = {
autoBrightnessValue: 100,
resultFunction: function (res) {
[].forEach.call(scannerLaser, function (el) {
fadeOut(el, 0.5);
setTimeout(function () {
fadeIn(el, 0.5);
}, 300);
});
scannedImg.src = res.imgData;
scannedQR[txt] = res.code;
UserCheckId();
}
};
function UserCheckId() {
$.ajax({
contentType: 'application/json; charset=utf-8',
crossDomain: true,
type: "POST",
dataType: "json",
url: '#Url.Action("UserCheckId", "Home")',
data: { qrcode: JSON.stringify(scannedQR[txt]) },
success: function (data) {
alert(data);
}
});
}
</script>
[HttpPost]
[AutoValidateAntiforgeryToken]
public ActionResult UserCheckId(string qrcode)
{
string result = qrcode;
return Json(result, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
i updated the code and showed where i am calling function "UserCheckId".
i found a solution.
I added below line in Startup.cs in Configure and it worked.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
Here is the Javascript code
$("#JSONPost").click(function (e) {
var jsonData = { name: "ramesh", mobile: "9xxxxxxxxx" };
$.post(
"/Trace/JSONPostMethod",
jsonData,
function (data, status) {
alert(status);
});
});
});
public ActionResult JSONPostMethod(object data)
{
}
data is coming as {} instead of the { name: "ramesh", mobile: "9xxxxxxxxx" }
Any idea how to get this JSON? I don't want to create a model class to get the data.
Found the solution. Inside the controller method do this,
var resolveRequest = HttpContext.Request;
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
You can modify your Json code and write something which is not confusing as below:
$("#JSONPost").click(function (e) {
var jsonData= {};
jsonData.Name = "Ramesh";
jsonData.Mobile = "9xxxxxxxxx";
$.ajax(
url: "/Trace/JSONPostMethod",
data: JSON.stringify(jsonData),
contentType: 'application/json',
type: 'POST',
success: function (data, status) {
alert(status);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Correction in your Controller:
[HttpPost]
public JsonResult JSONPostMethod(object data)
{
// your logic here
return Json(data, JsonRequestBehavior.AllowGet);
}
Hope this helps.
I have a JQuery function called InsertShowStudents() which is executed correctly every time a submit button() is pressed. On success, I'm calling the other function GetStudents() to show the updated list of elements in the table. The GetStudents() function just calls the controller action the first time the button is pressed. After that, InsertShowStudents() continues inserting in the table but the GetStudents() function doesn't invoke the Action Method on the controller.. I've used a breakpoint to prove it, do you know what's happening??
JQuery code:
$(function () {
$("#btnInsertStudent").click(function () {
InsertShowStudents();
return false;
})
})
function InsertShowStudents() {
$.ajax({
type:"post",
url: "/Students/InsertStudent/",
data: { Name: $("#Name").val(), LastName: $("#LastName").val(), Age: $("#Age").val() }
}).success(function () {
GetStudents();
//clear the form
$("#myform")[0].reset();
}).error(function () {
$("#divGetStudents").html("An error occurred")
})
}
function GetStudents()
{
$.ajax({
type: "get",
url: "/Students/GetStudents"
}).success(function (result) {
$("#divGetStudents").html(result)
})
}
Controller Actions:
public ActionResult InsertStudent()
{
return View();
}
[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult InsertStudent(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return View();
}
return View(student);
}
public PartialViewResult GetStudents()
{
List<Student> students = db.Students.ToList();
return PartialView(students);
}
In a situation like this where the first time is working I'd assume a cache problem. To force bypass the cache you can add the option to the ajax request. For more information check out the jquery ajax documentation
$.ajax({
type: "get",
url: "/Students/GetStudents",
cache: false
}).success(function (result) {
$("#divGetStudents").html(result)
})
Try this
function InsertShowStudents() {
$.ajax({
type:"post",
url: "/Students/InsertStudent/",
data: { Name: $("#Name").val(), LastName: $("#LastName").val(), Age: $("#Age").val() }
}).done(function () {
GetStudents();
//clear the form
$("#myform")[0].reset();
}).fail(function () {
$("#divGetStudents").html("An error occurred")
})
}
function GetStudents()
{
$.ajax({
type: "get",
url: "/Students/GetStudents"
}).done(function (result) {
$("#divGetStudents").html(result)
})
}
I am using MVC. In my one page, if i type one value that is process, if it exists the related details will populate in other all fields. how to do this in Ajax call?
Controller:
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return View("Call",partner);
}
Call is the Aspx page.
In view:
<script type ="text/javascript">
$('#getPincode').text('Get Pincode') // Sets text for company.
.attr('href', '#');
$("#getPincode").click(function () {
$('#getPincode').text('Get Company')
.attr('href', 'GetDetail?pincode=' + $('#Pincode').val());
});
$("#Pincode").blur(function () {
$("#checkPincode").trigger('click');
});
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
But i don't know how to populate the result into my view which means editor fields???
View:
<%:Html.TextBox("Address")%>
You can try this one:
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner, JsonRequestBehavior.AllowGet);
}
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = {'pincode': name};
$.ajax({
type: "POST",
url: "/GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
return it as a jsonResult
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner);
}
or if you want to load partial view load it as
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return PartialView("Call",partner);
}
<div id="myDiv"></div>
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
$('#myDiv').html(data);
}
});
return false
});
});
I am returning javascript from controller to view through ajax. but it gives me failure message, my code is given below.
My controller is
public ActionResult GetJava()
{
if (Request.IsAjaxRequest())
{
return JavaScript("<script>alert(\"some message\")</script>");
}
else
{
return View();
}
}
and view is
#{
ViewBag.Title = "GetJava";
Scripts.Render("~/bundles/jquery");
}
<h2>GetJava</h2>
<div><input type="button" value="GetJava" onclick="Getjavascript()" /></div>
<script type="text/javascript">
function Getjavascript() {
$.ajax({
url: '#Url.Action("GetJava","BindingJson")',
dataType: 'applicaiton/javascript;charset=utf-8',
type: 'Get',
data: 'script',
success: function (status) { status.value },
error: function (status) { alert("failure") }
});
}
</script>
What could be the possible issue?
You can create a script with src to your action, as suggested in this answer: https://stackoverflow.com/a/6778069/4251546
var script = $('<script />', {src: '#Url.Action("GetJava","BindingJson")'});
$(document).append(script)