Use string format in razor view to concat javascript variables - asp.net-mvc

How can I write
var releaseName = $('#SelectedReleaseId option:selected').text()
var templateName = $('#SelectedTemplateId option:selected').text()
this:
$("#TestplanName").text(releaseName + '-' + templateName + '-' + '#Model.UserId' + '-' + '#Model.CreatedAt');
into:
$("#TestplanName").text( '#string.Format("{0}-{1}-{2}-{3}",releaseName,templateName,#Model.UserId,#Model.CreatedAt)');
The releaseName and templateName are unknown...

You can't.
You're trying to mix client-side variables – which only exist in Javascript on the client – with server-side code.
Instead, you can use a Javascript equivalent of string.Format.

Related

How can I escape " or ' when it is a variable in ruby or rails?

I'm building a js file on the backend for future use and need to convert macros into js code. My gsub in the method below was working fine until I had a url with double quotes. If I have a variable quote_type = "'", how can I interpolate that as an escaped quote? In other words..
"'" becomes "\'" and '"' becomes '\"'
Here's my existing method and I just added the quote_type variable to try this out.
def substitute_timestamp_macro!(string)
quote_type = string[0]
string.gsub('[timestamp]', '\' + new Date().getTime() + \'')
end
edit: example string would be "https://doesntmatter.com/stuff/123;time=[timestamp]?"
edit 2: Here is the expected result:
"https://doesntmatter.com/stuff/123;time=" + new Date().getTime() + "?"
here is the actual result
"https://doesntmatter.com/stuff/123;time=' + new Date().getTime() + '?"
notice in my gsub i hard coded an escaped single quote. I now want to use the variable to match the input quote so if it's single, use single, and if double, use double
Consider %() to wrap your string:
def substitute_timestamp_macro!(string)
%("#{string}").gsub("[timestamp]", %(" + new Date().getTime() + "))
end
Note that this will render a string with escaped double quotes:
substitute_timestamp_macro!("https://doesntmatter.com/stuff/123;time=[timestamp]")
=> "\"https://doesntmatter.com/stuff/123;time=\" + new Date().getTime() + \"?\""
Which will be interpreted properly when you render this to a buffer:
puts substitute_timestamp_macro!("https://doesntmatter.com/stuff/123;time=[timestamp]")
=> "https://doesntmatter.com/stuff/123;time=" + new Date().getTime() + "?"
The surrounding quote characters of the value determine the behavior of this function, this should fit the bill:
def substitute_timestamp_macro!(string)
quote_type = string[0]
string.gsub('[timestamp]', "\\#{quote_type} + new Date().getTime() + \\#{quote_type}")
end

Enter bold tags in razor statement (#)

I am trying to enter bold tags in the following statement but they are not rendering properly.
#(user.AlternateId.Count() > 1 ? id.Value + "<b> ( </b>" + id.Key.Substring(0,3) + "<b> ) </b>" : id.Value)
Help is much appreciated!
This should work.
#if user.AlternateId.Any())
{
#id.Value <b>(</b> #id.Key.Substring(0,3) <b>)</b>
}
else
{
#id.Value
}
I am hoping that your id.Key will always have a length of 3+ chars ,otherwise the call to SubString is going to give you an exception. If you are not sure about that ,you might consider writing a custom Substring method (an extension method) which check the string length before trying to do the SubString operation as explained in this post.
For string values, Razor automatically HTML encodes any HTML. To counter this, you need to convert the string to IHtmlString. The easiest way to do that is to just wrap the return in Html.Raw:
#Html.Raw(user.AlternateId.Count() > 1 ? id.Value + "<b> ( </b>" + id.Key.Substring(0,3) + "<b> ) </b>" : id.Value)
Alternatively, you can simply create an instance of MvcHtmlString (which implements IHtmlString):
#(new MvcHtmlString(user.AlternateId.Count() > 1 ? id.Value + "<b> ( </b>" + id.Key.Substring(0,3) + "<b> ) </b>" : id.Value))
For your specific use case, here, Html.Raw is more intuitive, but in other scenarios (such as HtmlHelper extensions) it can be helpful to know that you can just return an instance of MvcHtmlString.

403 Invalid token error on GET user info

UPDATE: I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now.
I'm new to Valence. I have some Salesforce Apex code (written by someone else) that creates a D2L user. The code is working fine.
I want to add an Apex method to retrieve info for an existing D2L user using the userName parameter. I've copied the existing method, changed to a GET, set the query parameter to userName, and kept everything else the same.
When I call my method, I get a 403 Invalid Token error.
Do I need to use different authorization parameters for a GET? For example, do I still need to include a timestamp?
Here's a portion of the Salesforce Apex code:
public static final String USERS = '/d2l/api/lp/1.0/users/';
String TIMESTAMP_PARAM_VALUE = String.valueOf(Datetime.now().getTime()).substring(0,10);
String method = GETMETHOD;
String action = USERS;
String signData = method + '&' + action + '&' + TIMESTAMP_PARAM_VALUE;
String userSignature = sign(signData,USER_KEY);
String appSignature = sign(signData,APP_KEY);
String SIGNED_USER_PARAM_VALUE = userSignature;
String SIGNED_APP_PARAM_VALUE = appSignature;
String endPoint = DOMAIN + action + '?' +
APP_ID_PARAM + '=' + APP_ID + '&' +
USER_ID_PARAM + '=' + USER_ID + '&' +
SIGNED_USER_PARAM + '=' + SIGNED_USER_PARAM_VALUE + '&' +
SIGNED_APP_PARAM + '=' + SIGNED_APP_PARAM_VALUE + '&' +
TIMESTAMP_PARAM + '=' + TIMESTAMP_PARAM_VALUE;
HttpRequest req = new HttpRequest();
req.setMethod(method);
req.setTimeout(30000);
req.setEndpoint(endPoint);
req.setBody('{ "orgDefinedId"' + ':' + '"' + person.Id + '" }');
I thought I had to pass the parameters as a JSON string in the request body, but actually I need to put them on the URL (the endpoint string), so it's working now

how to read parameter with window.open in asp.net MVC3

I need to call an ASPX page from MVC view through below JavaScript code, also need to pass some parameter as query string,
function OpenTest() {
var width = (screen.availWidth - 700).toString();
var height = (screen.availHeight - 100).toString();
var param1 = "Test";
var baseUrl = '#Url.Content("~/Test/Test.aspx?")';
window.open(baseUrl + "param1=" + param1);
}
In ASPX page,
if(!string.IsNullOrWhiteSpace(Request.QueryString["param1"]))
{
string s1 = Request.QueryString["param1"];
}
I am able to call ASPX page and read parameter value by above code, but when I add other property of "window.open", I am not able to read query string, question is where should I place below property in above code so that I can also read query string value in ASPX page,
"mywindow", "width=" + width + ",height=" + height + ",toolbar=no,location=no,directories=yes,status=no," +
"menubar=no,scrollbars=yes,copyhistory=yes,resizable=yes" + ",screenX=0,screenY=0,left=0,top=0"
The syntax for window.open() is:
window.open('url/for/page/here.aspx', 'targetName', 'options');
The targetName can be "_self", "_blank", "_parent", just like any target attribute for links, or have an identifier to name the window, so you can reuse the window when openning with the same name.
When you calll window.open() with any option to restrict the window, like width=100 it assumes that all the other have to be disabled, so you don't have to put the properties you want to disable.
Fixing your options would be:
window.open(baseUrl + "param1=" + param1,
"mywindow",
"width=" + width + ",height=" + height + ",directories=yes,scrollbars=yes,copyhistory=yes,resizable=yes,screenX=0,screenY=0,left=0,top=0");
Another thing to note is that all options have to be separated by comas, without spaces. Some browsers ignore/missinterpret options with spaces.
Also, don't forget to escape the variables to pass with the url.

jQuery $.post - do I have to encode the URL parameter?

I'm making an AJAX call with $.post(url, cb). The URL I'm passing in could potentially have weird characters like spaces, &, ? and so on.
Do I have to use $.post(encodeURIComponent(url), cb)?
url is something like /foo/weird-char§.
Do I have to use $.post(encodeURIComponent(url), cb)?
You will have to use encodeURIComponent() but not on the entire URI, only on the data part (weird and chars in your example). The URL and the ? & separating the parameters must stay intact. If you encode the entire URI, it will become unusable.
If you would add the data as POST data using the data parameter:
url = "/foo/possible";
$.post(url, { "weird": "f2(90§§$", "chars": "ß1028490" });
jQuery's Ajax functions would take care of URL encoding the data automatically.
Yes, you would need to encode the keys and values in the query string (but not the ? which separates the path from the query arguments and the & which separates the query arguments). This is built into jQuery if you use the data parameter of the $.post, like so:
$.post(url, { name: "John", time: "2pm" }, cb);
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});

Resources