AllramEst
AllramEst

Reputation: 1449

Unable to get the query string data

I am trying to get two query string parameters from JavaScript to the controller. Here is the code:

JavaScript

var startDate = "",
    enddate = "";

var startDate = $.datepicker.formatDate(dateFormat, $("#startDate").datepicker('getDate'));
var enddate = $.datepicker.formatDate(dateFormat, $("#endDate").datepicker('getDate'));

if (startDate != "" || enddate != "") {
  window.location = `${window.location.href}/Index?startDate=${startDate}&endDate=${enddate}`;

}

C#

public IActionResult Index([FromQuery(Name = "startDate")] string startDate = "", [FromQuery(Name = "endDate")] string endDate = "") 
{    
}

The controller gets called, and the first parameter is fin but the second parameter gets a messed up version of the URL. Here is a picture. I am having a hard time figuring out what I am doing wrong.

JavaScript Values

enter image description here

C# values

enter image description here

Upvotes: 2

Views: 227

Answers (2)

AllramEst
AllramEst

Reputation: 1449

I solved it by removing the "index" in the url. The MVC framework automatically searches for the "index" ActionResult if the Action is missing in the url.

window.location = `Salaries?startDate=${startDate}&endDate=${endDate}`;

it also works like this:

window.location = `?startDate=${startDate}&endDate=${endDate}`;

Upvotes: 0

SBFrancies
SBFrancies

Reputation: 4250

From what you've posted it seems likely that windows.location.href is the problem and you are concatenating onto values which already exist in the URL. For example if your href was

http://www.somesite/Index?startDate=1&endate=2

Then your concatenated string would be:

http://www.somesite/Index?startDate=1&endate=2/Index?startDate=1&endDate=2

and your values would be:

startDate: 1
endDate: 2/Index/startDate=1

To solve the problem you could try using window.location.hostname instead of href.

Update

I think you should make the URL relative:

window.location = `/Index?startDate=${startDate}&endDate=${enddate}`;

Upvotes: 3

Related Questions