How to call URL action in MVC with javascript function?
Asked Answered
E

5

10

I´m trying to render url action with javascript in an MVC project. I capture an event on my page which calls this function but I´m not sure how to call this certain URL.

Can anyone help me please? :)

function onDropDownChange(e) {
    var url = '/Home/Index/' + e.value;
    //What now...?
}

-----------Edited-----------------------

Here´s my controller action:

    public ActionResult Index(int? id)
    {
        var tmpToday = DateTime.Now;
        var today = new DateTime(tmpToday.Year, tmpToday.Month, tmpToday.Day, 0, 0, 0);

        if (id != null)
        {
            var num = id.GetValueOrDefault();
            var rentableUnits = new List<Unit>();
            _unitLogic.GetAllRentableUnitsByArea(num, rentableUnits);

            var allAvailabilities = new ShowAvailability[rentableUnits.Count];

            for (int i = 0; i < rentableUnits.Count; i++)
            {
                var sTime = GetFirstDayOfMonth(today);
                var eTime = GetLastDayOfMonth(today);
                allAvailabilities[i] = new ShowAvailability(sTime, eTime.AddHours(23.0).AddMinutes(59.0), rentableUnits);
                today = today.AddMonths(1);
            }

            var showAvailability = new List<ShowAvailability>(allAvailabilities);

            return View(new HomeFormViewModel(showAvailability));
        }
        else
        {
            var allAvailabilities = new ShowAvailability[12];

            for (int i = 0; i < 12; i++)
            {
                var sTime = GetFirstDayOfMonth(today);
                var eTime = GetLastDayOfMonth(today);
                allAvailabilities[i] = new ShowAvailability(sTime, eTime.AddHours(23.0).AddMinutes(59.0));
                today = today.AddMonths(1);
            }

            var showAvailability = new List<ShowAvailability>(allAvailabilities);

            return View(new HomeFormViewModel(showAvailability));
        }
    }
#

I´m using Telerik extension for my DropDownList which fires the javascript function, this is in fact a Razor View:

 @(Html.Telerik().DropDownList()
     .Name("DropDownList")
     .Items(area =>
         {
             area.Add().Text("Öll svæði").Value("0").Selected(true);
             foreach (Unit a in Model.Areas)
                {
                     area.Add().Text(a.Name).Value(a.UnitID.ToString());
                }
         })
     .HtmlAttributes(new { style = "width: 130px;" })
     .ClientEvents(clev => clev.OnChange("onDropDownChange"))
     )

Here´s the script:

function onDropDownChange(e) {
    var url = '/Home/Index/' + e.value;
    $.ajax({
            type: "GET",
            url: url,
            data: {},
            dataType: "html"
        });
}
Emmalineemmalyn answered 24/1, 2012 at 19:18 Comment(5)
How are you calling onDropDownChange? What does e corresponds to?Daven
are you looking for ajax call or new page load? have you tried googling for "javascript call new url"?Skirting
What do you mean call? Reload the page to a new one, or obtain the data from that url without refreshing?Heeley
I´m trying a new page load, and the e stands for the id value needed to complete the url, for instance like this: localhost:111/home/index/20Emmalineemmalyn
Basically if I could render this action from javascript: @Url.Action("Index", "Home", new {id = e.value}) ...that would be perfect :)Emmalineemmalyn
S
12

Within your onDropDownChange handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success and error options. In the success option, use the data contained in the data argument to do whatever rendering you need to do. Remember these are asynchronous by default!

function onDropDownChange(e) {
    var url = '/Home/Index/' + e.value;
    $.ajax({
      url: url,
      data: {}, //parameters go here in object literal form
      type: 'GET',
      datatype: 'json',
      success: function(data) { alert('got here with data'); },
      error: function() { alert('something bad happened'); }
    });
}

jQuery's AJAX documentation is here.

Saddlery answered 24/1, 2012 at 19:36 Comment(0)
I
13

I'm going to give you 2 way's to call an action from the client side

first

If you just want to navigate to an action you should call just use the follow

window.location = "/Home/Index/" + youid

Notes: that you action need to handle a get type called

Second

If you need to render a View you could make the called by ajax

//this if you want get the html by get
public ActionResult Foo()
{
    return View(); //this return the render html   
}

And the client called like this "Assuming that you're using jquery"

$.get('your controller path', parameters to the controler , function callback)

or

$.ajax({
    type: "GET",
    url: "your controller path",
    data: parameters to the controler
    dataType: "html",
    success: your function
});

or

$('your selector').load('your controller path') 

Update

In your ajax called make this change to pass the data to the action

function onDropDownChange(e) {
var url = '/Home/Index' 
$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            //put your code here
        }
    });
}

UPDATE 2

You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div in your view and do something like this

in the view where you are that have the combo in some place

<div id="theNewView"> </div> <---you're going to load the other view here

in the javascript client

$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

With this i think that you solve your problem

Indigestive answered 24/1, 2012 at 19:37 Comment(8)
Thank you for your answer Jorge. I´ve been trying the $.ajax example you gave me. I have stepped through my code and everything seems fine until my View() has finished loading, that is, the page doesn´t seem to refresh (maybe I´m using it wrong). Should I put the full path into the url parameter, like this --> url: '/Home/Index/' + e.value or like this --> url: '/Home/Index/' with this data: e.value ?Emmalineemmalyn
could you please update your question and show me the controller associated? and how it's your routing...Indigestive
Hello again, yes I´ve edited my post. I hope this makes any sense :/Emmalineemmalyn
Thanx Jorge, this seems to be working fine now, at least mostly :) Although my problems aren´t completely over because there seems to be something wrong with my routing, my data seems to go in all the right directions, but my page doesn´t refresh. When I write the correct url in the web browser then everything shows up correctly, for instance --> localhost/Home/Index/20, but not with the DropDownList, I saw with break-point that the action was called with right parameters, I´m not sure, perhaps I need to check my Global.asax and see if I need to change the url routing in any way?!Emmalineemmalyn
update you question and show me how you're handling the callback of the ajax called first, also check with charlesproxy.com which are error are throwing the server. Instead of modified the routingIndigestive
That´s the thing, I´m embarrased to say this but I think I am really misunderstanding the callback because I´ve been doing it like this: --> success: function () { window.location.reload( true ); } <-- when in fact you would really need something like this: --> success: function () { callback.loadUrl('/Home/Index/20'); } <-- but I really am not sure how to get to this, or how the correct syntax is.Emmalineemmalyn
Excellent! That did the trick! You are a life-safer :) Thank you for your help, I hope I can return the favor later.Emmalineemmalyn
it should be id : e.value not id = e.value.Celinecelinka
S
12

Within your onDropDownChange handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success and error options. In the success option, use the data contained in the data argument to do whatever rendering you need to do. Remember these are asynchronous by default!

function onDropDownChange(e) {
    var url = '/Home/Index/' + e.value;
    $.ajax({
      url: url,
      data: {}, //parameters go here in object literal form
      type: 'GET',
      datatype: 'json',
      success: function(data) { alert('got here with data'); },
      error: function() { alert('something bad happened'); }
    });
}

jQuery's AJAX documentation is here.

Saddlery answered 24/1, 2012 at 19:36 Comment(0)
S
4

try:

var url = '/Home/Index/' + e.value;
 window.location = window.location.host + url; 

That should get you where you want.

Skirting answered 24/1, 2012 at 19:32 Comment(1)
In response to the above posted comments - url = '/home/Index/' + e.value; - what if e.value contains sensitive information that you don't want seen in the url? How do we conceal that?Dipsomaniac
M
1

Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:

 <input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />

Then you just get the value in your ajax call:

var path = $("#GetIndexDataPath").val();
$.ajax({
        type: "GET",
        url: path,
        data: { id = e.value},  
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.

Mitziemitzl answered 5/2, 2019 at 23:48 Comment(0)
C
1

Try using the following on the JavaScript side:

window.location.href = '@Url.Action("Index", "Controller")';

If you want to pass parameters to the @Url.Action, you can do this:

var reportDate = $("#inputDateId").val();//parameter
var url = '@Url.Action("Index", "Controller", new {dateRequested = "findme"})';
window.location.href = url.replace('findme', reportDate);
Coplin answered 4/6, 2020 at 19:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.