[jquery] How to call URL action in MVC with javascript function?

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"
        });
}

This question is related to jquery asp.net-mvc razor

The answer is


try:

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

That should get you where you want.


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.


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);

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


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC