I'm trying to build window.location.href passing a 1 entry query string.
The MVC action method expects that entry to be an integer.
I can hardcode a '2' and it works. Of course I do not want to hardcode.
So I get the value and set a variable and attempt to pass that variable using either of the 2 cases below but it fails. I get:
{0}The parameters dictionary contains a null entry for parameter 'blogCategoryId' of non-nullable type
'System.Int32' for method 'System.Web.Mvc.ActionResult BlogsForMaintIndex(Int32)' in
'GbngWebClient.Controllers.AdminFunctions.BlogMaint.BlogMaintController'. An optional parameter must
be a reference type, a nullable type, or be declared as an optional parameter.
How do I build it properly?
Here is the JavaScript:
$(function () {
$('#buttonClose').on('click', function () {
$('#modalView').modal('hide');
// The action method expects an integer.
var blogCategoryId = #Convert.ToInt32(Session["BlogCategoryId"]);
alert('blogCategoryId: ' + blogCategoryId);
// WORKS!
//window.location.href = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=2";
// Neither of these 2 work.
//window.location.href = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=blogCategoryId";
window.location.href = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=' + blogCategoryId + '";
})
})
Here is the simplified action method:
[HttpGet]
public ActionResult BlogsForMaintIndex(int blogCategoryId)
{
}
Try this
let myurl = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=" + blogCategoryId;
window.location.href = myurl;
Related
In my form I have a textbox as below
#Html.TextBox("first_name")
I need to pass the value of this textbox to controller through a actionlink.
I tried the below
#Html.ActionLink("View", "view_Details", new { name = first_name})
but this is giving error
"first_name" does not exist in the current context
Is this possible using a Actionlink?
My controller signature is
public ActionResult view_Details(string name)
{
return View();
}
Edited
#Html.ActionLink("View", "view_Details", new { name = getname()})
<script type="text/javascript">
function getname() {
return $("#first_name").val();
}
</script>
I tried above code. Its also giving error
getname() does not exist in the current context
You need javascript/jquery to get the value of the textbox and then update the url you want to redirect to
Html
#Html.ActionLink("View", "view_Details", new { id = "myLink" }) // add id attribute
Script
$('#myLink').click(function() {
var firstname = $('#first_name').val(); // get the textbox value
var url = $(this).attr('href') + '?name=' + firstname; // build new url
location.href = url; // redirect
return false; // cancel default redirect
});
Side note: further to you edit, the reason you receive that error is that razor code (the #Html.ActionLink() is parsed on the server before its sent to the view but getname() is a client side method which does not exist at that point - i.e it does not exist in the current context
I am trying to construct a URL using a HTML helper extension method while trying pass in parameters to the extension method. For example
public static MvcHtmlString GenerateActionLink(this HtmlHelper html,string displayText,string id,int logicstatusId)
{
var actionName = string.Empty;
var controllerName = string.Empty;
if (logicstatusid == 5)
{
actionName = "Basic";
controllerName = "HighBasic";
}
else
{
action = "Advanced";
controllerName = "HighAdvanced";
}
var targetURL = UrlHelper.GenerateUrl("Default", action, controller, new RouteValueDictionary(new { id = id}), RouteTable.Routes, html.ViewContext.RequestContext, false);
//Create the hyper link tag
var anchorLinkBuilder = new TagBuilder("a");
//Merge the target URL with the href attribute
anchorLinkBuilder.MergeAttribute("href", targetURL);
return MvcHtmlString.Create(anchorLinkBuilder.ToString(TagRenderMode.Normal));
}
While this helper method is working, the problem I am facing is on the client side.
var cellHtml = '<div class="action-column">';
var id= row.encryptedId;
cellHtml += '#Html.GenerateHtmlLink("Blip","'+ id+'" , 4)';
cellHtml += "</div>";
return cellHtml;
In this case the URL is getting constructed but the id parameter is not passing on to the helper method. I am not sure if I have done the passing of the parameter the right way. I'd appreciate if anybody help out.
Your C# code (call to the GenerateActionLink helper method) gets executed in server when razor tries to render the view. At that time the js variable value will not be there. The output of razor executing all the C# code view file is just the html markup which the browser will render. Only after that your javascript will be executed and the js variable value will be avaialble.
If you absolutely need to generate the dynamic url (for each id/logicstatusId value) in your client side javascript code using the UrlHelper method, you might consider exposing that C# code via an action method. Whenever you need the link url in your javascript code, make an ajax call to the action method, pass the parameter value and get the url.
public string GenerateActionLink(string id, int logicstatusId)
{
var actionName = "Advanced";
var controllerName = "HighAdvanced";
if (logicstatusId == 5)
{
actionName = "Basic";
controllerName = "HighBasic";
}
var targetUrl = UrlHelper.GenerateUrl("Default", actionName, controllerName, new RouteValueDictionary(new { id = id }), RouteTable.Routes, Request.RequestContext, false);
return targetUrl;
}
And in client side
var id = 1;
$.get('/Home/GenerateActionLink?logicstatusId=5&id=' + id,function(res) {
var htmlMarkup = 'Blip';
// do something with htmlMarkup
// Ex : $('#SomeDivId').append(htmlMarkup);
});
But if you want to do this for many items, you might not want to make a call for each items, In that case,I would generate the base links and conditionally append the querystring values in javascript
var baseUrlBasic = "#Url.Action("Basic","HighBasic");
// Now later
var id = 1;
var newUrl = baseUrl+'?logicstatusId=5&id='+id;
// Use this to build the anchor tag
This is my C# WebAPI2 controller, which gets hit:
[HttpGet, Route("bycaseidlist/{idArray}")]
public async Task<IHttpActionResult> GetByCaseIdList([FromUri] List<int> idArray)
This is the call:
var idArray = [4,4,2,4];
var url = baseUrl + 'api/cases/bycaseidlist/' + idArray ;
$http.get(url)
The problem is that the API doesn't get the array, it gets ...this:
In other words an array with one value: 0. Why is this happening? How do I fix it? It seems to be in-line with this answer, but it doesn't work. Should I pass it in the body? I feel like I am missing something obvious.
Get ActionMethods can take objects as arguments. However, the default behavior is to look at the body when the parameter is not a .net primitive. In order to force the action method to use a model binder to read the object data from the request, the parameter can be decorated with the [FromUri] or [ModelBinder] attributes. (Note there are other ways to do this that include doing parameter binding rules but that is probably overkill for what you are trying to accomplish here). Here is an implementation that solves the original problem that you were posing.
<script type="text/javascript">
var ajaxCall = function (myArry) {
var ajaxProperties = {};
ajaxProperties.url = "/api/Mul/Mutiply";
ajaxProperties.type = "Get";
ajaxProperties.data = {};
ajaxProperties.data.numbers = myArry;
ajaxProperties.contentType = "application/json";
console.log(ajaxProperties);
ajaxProperties.success = function (data) {
console.log(data);
}
ajaxProperties.error = function (jqXHR) {
console.log(jqXHR);
};
$.ajax(ajaxProperties);
};
var getData = function (e) {
var myArry = new Array();
myArry.push($('input[name=num1').val());
myArry.push($('input[name=num2').val());
ajaxCall(myArry);
return false;
};
</script>
Controller
[HttpGet]
public IHttpActionResult Multiply([FromUri] int[] numbers)
{
int result = 0;
if(numbers.Length > 0)
{
result = 1;
foreach (int i in numbers)
{
result = result * i;
}
}
return Ok(result);
}
}
I think my mistake was using Get. I might be remembering incorrectly (someone confirm if you know offhand), but Get might not be able to take objects as arguments. Anyway, I changed the method to POST and then changed the param to be sent in the request body, rather than the url. It now works. Here is the working code:
[HttpPost, Route("bycaseidlist")]
public async Task<IHttpActionResult> PostByCaseIdList([FromBody] int[] sqlCaseIdArray)
and the call itself:
function runDbCall(url, sqlCaseIdArray){
return $http({
method: 'POST',
url: url,
data: sqlCaseIdArray
});
}
runDbCall(url, sqlCaseIdArray)
I will come back to this when I figure out if the problem was Get not being able to take objects, but I thought it could in url, just not in body...need to clarify. If someone posts an answer just on that part, I will accept, since that's probably the root of the prob.
I am using history.pushState to append few params to current page URL after making an AJAX call on my page. Now on same page based on user action, I want to update the page URL again with same or additional set of params. So my code looks like this:
var pageUrl = window.location.href + "?" + queryString;
window.history.pushState('','',pageUrl);
queryString is my list of query params.
For example, My Default page URL: http://sample.com/
After First AJAX call on same page URL should be: http://sample.com?param1=foo¶m2=bar
After Second AJAX call on same page URL can be:
http://sample.com/?param1=foo,foo1¶m2=bar¶m3=another_foo
But with the above code my params are getting appended to URL with the params and they look like below after second AJAX call:
http://sample.com?param1=foo¶m2=bar¶m1=foo,foo1¶m2=bar¶m3=another_foo
So the params appear twice in the URL, is there any way of replacing the params in URL before pushing to History or any other better way to achieve this in javascript(jquery) ?
I think what you need is remove window.location.href and leave '?' +.
var pageUrl = '?' + queryString;
window.history.pushState('', '', pageUrl);
This function might be helpful
function updateUrlParameter(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
window.history.pushState("", "", newUrl);
}
Edit: The following solution is simpler, and it also works if the parameter is not yet part of the URL. However, it's not supported by Internet Explorer (you don't say?).
function setQueryStringParameter(name, value) {
const params = new URLSearchParams(window.location.search);
params.set(name, value);
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
}
In order to keep the last part of the url and just play with parameters, you can create a new URL object like so:
// e.g url: sample.com/testpage/test
var url = new URL(window.location);
url.searchParams.set('foo', 'bar');
window.history.pushState({}, '', url);
// outcome: sample.com/testpage/test?foo=bar
// you can remove, just the param part, like so:
url.searchParams.delete('foo');
Manage query parameters in the current URL
This function is similar to the other answers, but without using RegExp and string concatenations.
Args:
name - string name of the query parameter.
value - string value of the parameter.
append - if true: this function always adds a new parameter. This is very useful when you need to add two parameters with the same name, e.g.: localhost:8080/some_page?foo=100500&foo=ABC. Otherwise, the parameter will be changed (or added if absent).
function setQueryStringParameter(name, value, append=false) {
const url = new URL(window.document.URL);
if (append) url.searchParams.append(name, value);
else url.searchParams.set(name, value);
window.history.replaceState(null, "", url.toString());
}
I have a scenario to get Query Params from the URL. There is a method called toQueryParams() which will get all params.
But when the URL is http://www.google.com the same method returning the same URL as query param, URL as key and undefined as value.
var param = window.location.href.toQueryParams()
This is the code I have used.
When the URL has no query parameters ie no ? or & part of the URL then there are no query parameters except for the URL.
So how I usually use this method on a given URL http://www.mywebsite.com/index.php?arg=2500&search=Smith
var param = window.location.href.toQueryParams();
if(param.arg != undefined)
{
//do things with the arg parameter
}
if(param.search != undefined)
{
//do things with the search param
alert('User has selected '+param.search+' as the search parameter');
}
So if the given param does not exist then I don't try and handle it. The method toQueryParam() is giving you a error you can handle instead of an Exception or full on JS error that stops your JS execution.
I tried in the following way, to resolve this issue.
if (window.location.search != "") { // this means the url has no query params
var param = window.location.href.toQueryParams(); // param Object will holds queryparams in key and value form
} else {
var param = new Object(); // param will has no queryParmas but, it is an empty object
}