I rendering page with some tabs with content (inside tabs) dynamicly.
So I got
<div id="UpdateBlock">
#Html.Action("GeneratorTemplate", "FormTemplate", new { id = 8 })
</div>
it calls
public ActionResult GeneratorTemplate(int id)
{
//Description desk = new Description();
return PartialView("~/Views/FormTemplate/GeneratorTemplate.cshtml");
}
I want to make something like this
<div id="UpdateBlock">
#Html.Action("GeneratorTemplate", "FormTemplate", new { openedtab = getActiveTab() })
</div>
public ActionResult GeneratorTemplate(int openedtab)
{
return PartialView("~/Views/FormTemplate/GeneratorTemplate.cshtml", openedtab);
}
And there in partialview call ajax function with openedtab parameter. Like this
var g_id = openedtab;
function updateGenerators(g_id) {
var g_list;
$.ajax({
async: false,
url: '/Generator/GetCurrentGenerator',
type: 'POST',
data: {
generatorNumber: g_id
},
success: function (text) {
w2alert(text);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
I tried to call Js inside razor but it not works that way. How could I do what I need?
Using what I can access to data which I pass with return PartialView("~/Views/FormTemplate/GeneratorTemplate.cshtml", openedtab);?
Related
I have a problem when trying to make a request to a url created from mvc, this request is made to an actionresult of a controller, when I am in home ajax if it finds the address, but when I am in a site of my specific system , that is, I am in a section where the url is larger due to other parameters that are in the url, for example in a user profile, there ajax instead of finding the url that is linked to an actionresult return the html page, that is, return the html code, here are my codes
function guardarCalificacion(newidp, ratingp)
{
$.ajax({
type: 'POST',
url: 'saveRating',
data: {
newid: newidp,
rating: ratingp
},
beforeSend: function () {
},
success: function (data)
{
alert(data);
},
error: function ()
{ },
complete: function ()
{ }
});
}
and there are the route
routes.MapRoute(
"saveRating",
"saveRating/{newid}/{rating}",
new { controller = "Home", action = "SaveRating", id = UrlParameter.Optional }
);
in this url if it runs well
http://localhost:49439/Home/index
but in this it is not executed
http://localhost:49439/new/128/busqueda-numero-29
and finally the actionresult
public ActionResult SaveRating(int newid, int rating)
{
return Content(Methods.saveRating(newid, rating).ToString());
}
I have web application in ASP.NET MVC C#. I want to call Controller Action method with parameters from javascript but I get always null for parameters.
In .js I have:
$.ajax({
cache: false,
url: this.saveUrl,
type: 'post',
success: this.nextStep,
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
nextStep: function (response) {
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
if (response.redirect) {
ConfirmOrder.isSuccess = true;
location.href = response.redirect;
return;
}
if (response.success) {
ConfirmOrder.isSuccess = true;
window.location = ConfirmOrder.successUrl;
//window.location.href = #Url.Action("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" });
//window.location.href = '#Html.GetUrl("Completed", "Checkout", new { customerComment = "test", customerDate = "2018-12-31" })';
}
Checkout.setStepResponse(response);
}
in RouteProvider.cs I have:
routes.MapLocalizedRoute("CheckoutCompleted",
"checkout/completed/{orderId}/{customerComment}/{customerDate}",
new { controller = "Checkout", action = "Completed", orderId = UrlParameter.Optional, customerComment = UrlParameter.Optional, customerDate = UrlParameter.Optional },
new { orderId = #"\d+", customerComment = #"\w+", customerDate = #"\w+" },
new[] { "Nop.Web.Controllers" });
And finaly in Controller I have:
public virtual ActionResult Completed(int? orderId, string customerComment, string customerDate)
{
//some code here
}
I always get parameters value null and I don't know why. I try to call this Action with parameters on several diferent way like I saw on this forum but no success.
Did you add httpPost wrapper to your controller ?
[HttpPost]
public virtual ActionResult Completed(MyClass MyClassObj )
{
//some code here
}
in your Ajax code u didn't mention your Data type And Data try This Ajax
function Save () {
try {
var req = {
DeliveryCode: value,
}
$.ajax({
url: URL,
type: 'POST',
data: req,
dataType: "json",
async: true,
success: function (result) {
resetLoadWaiting()
},
error: function (e) {
}
});
}
catch (e) {
}
}
Mistake was in url string. Correct one is
ConfirmOrder.successUrl = "http://localhost:8079/checkout/completed/?customerComment=eee&customerEstimateShippingDate=2017-11-14"
I found this solution in this answer: Routing with Multiple Parameters using ASP.NET MVC
I dont need to update RouteProvider with new parameters. It is enough to put in in Controller Action method. Other things happen automatically.
I am learning web development. And I just want to make a simple AJAX GET call in ASP.Net MVC Application and I want visualize how it works. But I am not able to do so. I am a beginner and I could have done any silly mistakes. But as of now there are no errors in my code.
Below is what I have:
So, I have a Index.cshtml file which is already loaded. Now in that page I want to make an Ajax GET call to one of the function that I have written in the HomeController and action name is Test. I just want to hit the breakpoint in that Test Action of Homecontroller and return something back to the Success of AJAX Call.
In HomeController I have below Action
[HttpGet]
public ActionResult Test()
{
return View("hello");
}
jQuery
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
}
Confusion: Do I need to create a cshtml for Test. But I actually do not want that. I just want the Test Action to return me one data. And I will display that data in my Already opened Index.csthml file.
Error: No error but I am not able to hit the breakpoint in Test Action of controller. Kindly note that Success of AJAX is hitting but I do not see any data. But I am sure it did not hit the test Action breakpoint.
Change your action method like this
[HttpGet]
public JsonResult Test()
{
return Json("myContent",JsonRequestBehavior.AllowGet);
}
And in your success method in 'html' variable you will get back "myContent".
Example :
function RemoveItem(ItemId) {
if (ItemId && ItemId > 0) {
$.ajax({
cache: false,
url: '#Url.Action("RemoveItem", "Items")',
type: 'POST',
data: { id: ItemId },
success: function (result) {
if (result.success == true) {
$("#CartItemGridDiv").load('#Url.Content("~/User/Items/CartItemGrid")');
alert('Item Removed successfully.');
}
else {
alert('Item not removed.');
}
},
error: function (result) {
alert('Item not removed.');
}
});
}
}
public ActionResult RemoveItem(int id)
{
if (id > 0)
{
bool addToChart = false;
addToChart = Utilities.UtilityClass.RemoveItem(id);
if (addToChart)
{
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
public ActionResult CartItemGrid()
{
List<CartItems> oItemList = (List<CartItems>)Session[MvcMAB.StringConst.CartItemSession];
return View(oItemList);
}
Since you don't want to return a view, you might need to return Json() instead of View()
You need to Allow Get in the action. Like that:
public ActionResult SomeGetAction(int? id)
{
//Some DB query here
var myJsonList = myListQuery;
return Json(myJsonList, JsonRequestBehavior.AllowGet);
}
Or in case of just Simple string response:
public ActionResult SomeGetAction()
{
return Json("My String", JsonRequestBehavior.AllowGet);
}
I would recommend renaming html into response.
Also change that to this in Error Response section.
$.ajax({
url: '/Home/Test',
type: 'GET',
success: function (response) {
alert(response);
},
error: function (error) {
$(this).remove();
DisplayError(error.statusText);
}
});
Enjoy.
C#:
public JsonResult Test()
{
return Json("hello");
}
Jquery:
$.ajax({
url: '/Home/Test',
type: 'Post',
dataType: 'json',
success: function (html) {
alert(html);
},
error: function (error) {
alert(error);
}
});
I'm trying to fetch data from a controller and update my view using ajax.
This is my controller:
public class PatientController
{
DatabaseContext db = new DatabaseContext();
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.FirstOrDefault(p => p.Cpr == "2410911615");
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And this is my ajax call:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
dataType: 'json',
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
When i call the function i always get the error alert.
GET http://localhost:51140/Patient/GetPatientFromCpr 404 (Not Found)
Can someone point out what's wrong?
(EDIT)
I now get a new error after adding ": Controller"
GET http://localhost:51140/Patient/GetPatientFromCpr 500 (Internal Server Error)
Your 'PatientController' is not a Controller (it does not inherit from Controller)
public class PatientController : Controller
{
....
}
Inherit you PatientController with Base Controller Class
public class PatientController : Controller
In controller
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.where(p => p.Cpr == "2410911615").FirstOrDefault();
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And Specify the type of ajax calling
type: "POST" or type: "GET" ....
This will help you to fix error
Try using this, may be this works..!!
View:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
//dataType: 'json',
type:"POST", // GET or POST
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
Controller:
public class PatientController : Controller
{
....
}
So I am calling my action result method using this:
var url= "/Example/Controler/1/Action";
$("<form action='"+url+"'></form>").submit();
But the action Method is not called...
I have also tried this
$.post(url, function (data) {});
And this works, we call the controller, but then the page doesn't refresh...
My action method looks like this:
public ActionResult DoStuff(int Id)
{
.....
return RedirectToAction("index", new { Id });
}
You can use Ajax function as follows :
$.ajax({
url: "/Controler/Action",
data: { 'Id': groupId },
type: 'GET',
success: function (result) {
//do the necessary updations
},
error: function (result) {
}
});
You can also try form submission as follows :
#using (Html.BeginForm("Action", "Controller", FormMethod.GET))
{
// do your html
<input type="submit" value="save"/>
}