jQuery post to another controller - asp.net-mvc

If I have a Controller called "HomeController" and I'm on the Index page of that controller, how can I do a jQuery Ajax post to another controller.
I tried the below,
$.post("/DetailedQuote/jQueryGetDetailedQuote", { productCode: "LPJ" }, function(newHTML) {
alert(88);
});
I have a DetailedQuoteController.
I have also tried;
post("DetailedQuote/
post("DetailedQuote.aspx/
post("/DetailedQuote.aspx/
post("/DetailedQuoteController/
post("DetailedQuoteController/
post("DetailedQuoteController.aspx/
post("/DetailedQuoteController.aspx/
And still no joy.
I should also mention that this is running a Hybrid WebForms and MVC site on IIS 6.
EDIT
The error that is being returned in error: is "error" so I assume that's maybe a 404.
In fact, it is a 404. I just checked.

This should work:
public class DetailedQuoteController : Controller
{
[HttpPost]
public ActionResult GetDetailedQuote(string productCode)
{
return Json(new { Code = productCode, Quote = 123 });
}
}
And to invoke it first declare a global javascript variable containing the address of this controller somewhere inside the view:
var quoteAddress = '<%= Url.RouteUrl(new { controller = "DetailedQuote", action = "GetDetailedQuote" }) %>';
And finally call the method:
$(function() {
$.post(quoteAddress, { productCode: 'LPJ' }, function(json) {
alert(json.Quote);
});
});

There doesn't appear to be anything wrong with your jQuery command, so the most obvious place to start looking is in the controller itself. Things to check would be:
Does your Controller action return a Json response (e.g. public JsonResult jQueryGetDetailedQuote)?
Are you using the Json() method to return your object?
Do you have your action decorated with the [HttpPost] attribute?
Perhaps you could post part of your controller code as well?
I notice that in your jQuery method you're calling an action called jQueryGetDetailedQuote. If your intention is purely to just GET a result, then perhaps you should use jQuery's $.get() or $.getJSON() functions instead?

Related

void ActionMethod call using ajax post request with verificationtoken overwrites page, turning it blank. How come?

I am trying to call an action method without affecting the view. I call the following action method
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public void Index(LoginModel login)//, string returnUrl)
{
if (ModelState.IsValid &&
System.Web.Security.Membership.ValidateUser(login.UserName, login.Password))
{
FormsAuthentication.SetAuthCookie(login.UserName, login.RememberMe);
login.JavascriptToRun = "updateForm()";
}
// handle error
}
by doing this
$('#loginBtn').click(function () {
var success = false;
var form = $('#loginForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: {
__RequestVerificationToken: token,
LoginModel: "#Model"
},
success: function (result) {
alert("logged in");
}
});
});
The form is in a separate view which also contains above JS-code snippet.
Everything works fine except for that the entire page reloads and since the actionmethod is void this turns out blank. I do not want anything to happen to the webpage, only to change js code snippet stored in a model which BTW is an empty function as of now.
I've looked at related posts such as ASP.NET MVC - How to call void controller method without leaving the view? but I am none the wiser.
Feels like I'v hit a wall and others' input would be much appreciated. Cheers!
You can use ActionResult as a data type for Index() Action and use View() to return your javascript into it. (return JavaScriptResult())
Check out this too:
Working example for JavaScriptResult in asp.net mvc

OnClick event on different things like divs, img and so on then use data from those in controller to do something

I been googling for about two hours and couldn't find anything about it.
What does one use(frameowork or maybe it is already uilt up in mvc) to pass data from VIEW to controller.
For example lets say I have a list of products and I wanna delete it without refreshing a page just by clicking on the thing like <div data="23020id" onclick="doSomething()"></div> and so if I would press on that div, something would happen in controller without refreshing the page.
I don't know how to google it or what should I've been aiming for here.
I've seen that many websites does it but I don't really know what they use and how they do it.
Could someone give me any direction?
Let's start with your example.
lets say I have a list of products and I wanna delete it without
refreshing a page just by clicking on the thing like
<div data="23020id" onclick="doSomething()"></div>
Here it simply means you're calling javascript function doSomething() on click. But you can give Id to that div and perform click on that id.
<div id="test"data="23020id"></div>
Now what could be in the this function?
This function called your controller method via an ajax call, which will send Id to the controller which we need to delete.
javascript code:
$('#test').click(function() {
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:id},
success: function(data) {
// update some DOM element with the result returned by the
// server. So supposing that you have some <div id="someContainer">
// that will contain the part of the DOM you want updated:
},
error: function() {
alert("error");
}
});
});
Now when you click on button, that will call your controller method and pass id.
public ActionResult Delete(int Id)
{
// do delete here.
return Json(data);
}
Perform deletion on method and return view, and update it on ajax success.
I suggest you to use Partial View for such things. For more see here: Rendering a Partial View and JSON Data Using AJAX in ASP.NET MVC
you can try with this
you can not return View() from ajax call. you need to retrun Json()
you Action method
public ActionResult Delete(int Id)
{
// delete method call
return Json("success", JsonRequestBehavior.AllowGet);
}
your ajax call
$("#divId").click(function() {
var dataattr = $(this).attr("data"); //use this variable
$.ajax({
type: 'POST',
url: "/controller/Delete",
data:{Id:dataattr },
success: function(data) {
refresh your DOM element
},
error: function() {
alert("error");
}
});
});
you could use JQuery for that..
$("#divId").click(function() {
dataattr = $(this).attr("data"); //use this variable
$(this).hide();
});

ASP.NET MVC - Execute controller action without redirecting

I am trying to execute an action on a controller without redirecting to the associated view for that action. For a good example of what I am trying to achieve take a look at the music.xbox.com website. When you add a song to a selected playlist from a popup menu - the page just shows a notification without any redirect or refresh. how is this possible?
What I have is the following:
I have a _playlistPopupMenu partial view that renders the list of playlists as follows:
_PlaylistPopupMenu
#model List<OneMusic.Models.GetPlaylists_Result>
#if (Model.Count > 0)
{
<li style="height:2px" class="divider"></li>
foreach (var item in Model)
{
<li style="height:30px">#Html.DisplayFor(p => item.Name)
#Html.ActionLink(item.Name, "AddSong", "Playlist", new { playlistId = #item.PlaylistId, songId = 1 }, "")
</li>
}
}
The PlaylistController AddSong action is as follows:
public PartialViewResult AddSong(int? playlistId, int? songId)
{
if (ModelState.IsValid)
{
db.AddSongToPlaylist(playlistId, songId);
db.SaveChanges();
return PartialView("_AddToPlaylist", "");
}
return PartialView("_AddToPlaylist", "");
}
I am struggling with what to put in the _AddToPlaylist partial view which I think I need to be able to display a notification of some kind (Possiblly using PNotify add in for Bootstrap). MVC wants to always redirect to ../Playlist/AddSong?playlistId=1&songId=1
Any ideas on how to complete this last part of the problem would be great.
If you don't want "full page reloads" then you need to approach the problem slightly differently, using javascript to alter the page dynamically. A library such as JQuery might make manipulating the DOM a little easier.
Display the popup dynamically using javascript.
When the user hits OK/Submit on the popup, post the data back to the server using javascript, and have the controller you are posting to return some HTML.
Append the returned HTML block (partial view) to an existing div containing playlist tracks.
The most difficult part of this is the asynchronous post. Help with updating a div without reloading the whole page can be found in this question.
EDIT - Example
If you have a controller action (accepting POSTs) with the URL myapp.com/PlayList/AddSong/, then you'd set up JQuery to post to this URL. You'd also set up the data property with any form data which you'd like to post, in your case you'd add playistId and songId to the data property.
You'd then use the result of the AJAX query (HTML) and append it to the existing playlist HTML on the page. So assuming that you want to append the partial view's HTML to a div with ID playlistDiv, and assuming that your partial view returns HTML which is valid when appended to the existing playlist, then your javascript will look something like this:
var data = { playlistId: 1, songId: 1 };
$.ajax({
type: "POST",
url: 'http://myapp.com/PlayList/AddSong/',
data: data,
success: function(resultData) {
// take the result data and update the div
$("#playlistDiv").append(resultData.html)
},
dataType: dataType
});
Disclaimer: I can't guarantee that this code will work 100% (unless I write the program myself). There may be differences in the version of JQuery that you use, etc, but with a little tweaking it should achieve the desired result.
using System.Web.Mvc;
using System.Web.Mvc.Html;
public ActionResult Index()
{
HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
helper.RenderAction("Index2");
return View();
}
public ActionResult Index2(/*your arg*/)
{
//your code
return new EmptyResult();
}
in your controller you must add bottom code:
public ActionResult Index(string msg)
{
if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com"))
{
string html = "";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Encoding = Encoding.UTF8;
html = client.DownloadString("https://NewExampleUrl.com/first/index?id=1");
}
Response.Write(html);
}
...
}
your view must be empty so you add bottom code
#{
ViewBag.Title = "sample title";
if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com"))
{
Layout = null;
}else
{
Layout ="~/Views/Shared/_Layout.cshtml"
}
}
#if (Request.Url.ToString().Contains("yourNewExampleUrlWithOutRedirect.com")==false)
{
before view like :
<div>hello world</div>
}

$.post() not working if the mvc model view controller has a parameter

I´m new with MVC. I´m using MVC4.
I'm having an issue with a callback. If I alert before and after the post() call both alerts show but the call doesn't fire.
[HttpGet]
[Authorize]
public ActionResult Dashboard(int Menu)
{
//some code
return View("Dashboard");
}
<script>
$(document).ready(function () {
$.post("../Client/GetFact", {},
function (data) {
//some code
});
});
</script>
[HttpPost]
[Authorize]
public JsonResult GetFact()
{
//some code to fill object_data
var data = object_data;
return Json(data);
}
As long as I leave ActionResult Dashboard without a parameter is works. If I add a parameter to Dashboard(int Menu) then the call back to GetFact doesn't work.
I searched and found a similar post and follow the instructions given by you guys, but still does not work( looked at: getJSON not working if the mvc model view controller has a parameter).
I do not know what I'm doing wrong. Can you help? Thank's!
I do something similar with $.get, using jquery with the #Url.Action instead of the url.
in addition to using the FormContext to pass to my Action :
Place just before #using (Html.BeginForm())
#{ ViewContext.FormContext = new FormContext(); }
example :
$.get('#Url.Action("ActionName", "ControllerName")', { IDName: $('#IdName').val() }, function (data) {
//Do Something here with the data
});
I would imagine form post would be
$.post('#Url.Ation("ActionName", "ControllerName")', function (data) {
//Do Something here with the data
});
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ type: "POST",
url: url,
data: data,
success: success,// -> call alert here
dataType: dataType});

access the variable in my javascript from controller

In my CSHTML I have some JavaScript which contains a string variable. How do I access this variable from my controller?
When you invoke the controller you could pass it as parameter. For example if you are invoking the controller action using AJAX:
$.post('/someaction', { someValue: someVariable }, function() {
...
});
[HttpPost]
public ActionResult someAction(string id)
{
return Content("got it");
}
in script
$(function(){
var someid='12';
$.post('/Controller/someAction',{id:someid},function(data){
//this call back is executed upon successfull POST
console.log(data); // got it"
});
});
You can use a hidden input field in your form valorized with the value of your string variable. When you post the form you can read the value as usual.

Resources