MVC3 Change View from Jquery

11,820

Solution 1

Try

function productSelectedCallback() {
   var prodId = $(this).attr("id");
   var targetUrl = '/Product/Details/' + prodId.toString();
   $(this).load(targetUrl);
}

Edit:

Change your action method on your controller from

public ActionResult Details(string productId)
{
    return View();
}

to

public ActionResult Details(int id)
{
    return View();
}

or your jQuery code to:

function productSelectedCallback() {
   var prodId = $(this).attr("id");
   var targetUrl = '/Product/Details/?productId=' + prodId.toString();
   $(this).load(targetUrl);
}

You probably don't have a route setup to take "productId" in your action. You can still use it (if you don't want to configure the route) but it will need to be in a query string.

Edit 2:

In light of your last comment, I am not sure you really want to be using AJAX for your solution since you are attempting to redirect from one page to another. I would suggest changing your return type to a RedirectToAction result. This will tell the browser that you need to redirect, but this will need to be done in an action other than your product details action (or you will get an endless redirect loop).

Try something like this:

// In the home controller where Id = the product id
public ActionResult RedirectToProductDetails (int id)
{
    // Use whatever names you want for Id and ProductId, respectively
    return RedirectToAction ("Details", "Products", new { id = id });
}

// And then in your Product Controller:
public ActionResult Details (int id)
{
    var MyProduct = // Get your product from the database or whatever
    return View (MyProduct);
}

(Please note, this will actually cause two trips for the client, effectively removing any advantage of using an "AJAX" approach.)

Solution 2

JQuery Callback

function productSelectedCallback() {
   var prodId = $(this).attr("id");
    var BaseUrl = 'http://' + top.location.host ;

    $.ajax({
                type: 'POST',
                url: BaseUrl + '/Product/Details',
                data: ({ productId: prodId.toString() }),
                success: function (resp) {

                }
            });
}

CallJquery explode effect with callback:

$(".productOriginal").click(function () {
            $(this).hide("explode", {}, 1000, productSelectedCallback);
});

Here is my product controller:

public class ProductController : Controller
    {
        [HttpPost] 
        public ActionResult Details(string productId)
        {
            return View();
        }
    }
Share:
11,820

Related videos on Youtube

Ryand.Johnson
Author by

Ryand.Johnson

Updated on June 04, 2022

Comments

  • Ryand.Johnson
    Ryand.Johnson almost 2 years

    I am new to MVC3 and Jquery. Maybe i am not taking the right approach to this, please let me know if there is a better solution.

    I want to use JQuery to change views in my MVC app. I have a list of products on the main page. When the user clicks a product, I Jquery to send a request to the server with the product ID and change to a product details view. Before I change views, i do Jquery explode effect. I am using the callback function of the Jquery effect to submit the request. When i debug my code. The product details controller is called and it returns the details view. But the web browser does not change the the product details view. it stays on the home page.

    Here is my product controller:

    public class ProductController : Controller
    {
    
        public ActionResult Details(string productId)
        {
            return View();
        }
    }
    

    Jquery explode effect with callback:

    $(".productOriginal").click(function () {
                $(this).hide("explode", {}, 1000, productSelectedCallback);
    });
    

    Jquery Callback:

    function productSelectedCallback() {
       var prodId = $(this).attr("id");
       var data = { productId: prodId.toString() };
       $(this).load('/Product/Details');
    }
    

    In addition to .load, i have use .post and .ajax and got the same result with all. So, i must be fundamentally missing something here.

    I am using the default register routes. The products folder is set up the same as the home folder and has a details.cshtml.

    Thanks for you help!

  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    explode is jquery UI effect. I got the exact same result when i copied your code in. The only difference was that the product image faded away instead of exploding.
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    I got the same result with that. When i debug the code, I can see it hit the Product Controller and Details action. It returns the view. I can right click and select Go To View and get to the right View. I can also type ...../product/details into the URL of the web browser and load the correct page.
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    I tried taking product Id completely out of the picture. public ActionResult Details() { return View(); } function productSelectedCallback() { var prodId = $(this).attr("id"); var targetUrl = '/Product/Details/'; $(this).load(targetUrl); }
  • Jim D'Angelo
    Jim D'Angelo almost 13 years
    @Ryand - and what happened? Can you run it in debug mode with a break at the action method and see if it is even getting called? Are you getting an internal error or anything? Also, are you returning View() or PartialView()?
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    It gets to the controller. I have set a break point there and stepped through it. It returns a view. But the browser doesn't post back with the new page. it returns to the original. I also have tried the ajax route too with the httppost attribute. The same thing happens. I have stepped though it.
  • Jim D'Angelo
    Jim D'Angelo almost 13 years
    Symantically, that doesn't make much sense. A POST should not be used as a GET. This removes some of the HTTP goodness that creates built-in scalability.
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    @jdangelo Yes, the same thing happened. I did set a break point. I am return a View(); Any other ideas? Thanks!
  • Jim D'Angelo
    Jim D'Angelo almost 13 years
    I would recommend a PartialView (otherwise you will be returning a full webpage instead of just the little bit you're interested in). Try showing the element after the load is handeled. $(this).show(); Also, I would get FireBug or some other HTTP inspector so you can watch your calls go out and come back on the client side.
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    I tried that. When i set a break point on the action. it hits the actiona and returns the view. Just like the Load did. Here is the code i used to do the ajax call. The only difference I can see is that URL, I am not putting the base before it. But i think my ajax call is working given that is hit the controller and action.
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    here is the code $.ajax({ url: "/Product/Details", type: 'POST', data: JSON.stringify(data), dataType: 'json', contentType: 'application/json, charset=utf-8', async: false, beforeSend: function () { }, success: function (data) { }, error: function () { } });
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    I don't think a partial view is right. I want to move to a different controller all together. I want to go from the home controller to a products controller.
  • Jim D'Angelo
    Jim D'Angelo almost 13 years
    Oh, I see, my apologies. Why are you using AJAX then? If you're attempting to use this as a redirect, there are better solutions. The $.load() that you're using is to present a small snippet of data into something like a <div>. To get this to work, though, just return a RedirectToAction result.
  • Ryand.Johnson
    Ryand.Johnson almost 13 years
    @jdangle, that helped me solve it. You are right. No reason to post anything to the server. I already have the product Id. I can redirect from the client. Thanks for your help!
  • andres descalzo
    andres descalzo almost 13 years
    you can test the code to see the product code and the result, and check if it works, then you have to see where to send the result.
  • rkaregaran
    rkaregaran almost 13 years
    @Ryand.Johnson This might sound like a stupid question, but are you pushing the resulting view into the HTML DOM (are you doing anything with the view?) The browser won't automatically do anything after an AJAX call, you get the response and then do stuff with it.