I have a variable in JavaScript and I want to use it as an index reference in my C# code. How do I convert the JavaScript variable into something C# can use? So far this is what I have..
#{
var selectedStockLocation = #Html.Raw(Json.Decode(document.getElementById("cbLocation " + id).value));
var currentLocation = Model.StockLocationBinData[selectedStockLocation];
}
You will have to post the value back with either a full POST or an AJAX call.
You are mixing server and client code there.
You need to use (one of many) methods to post client data back to the controller.
Use jquery to write to a hidden variable in the form is one route, see this answer:
Passing a jQuery value to MVC 3 Razor view html helper
JavaScript runs well after the server-side code has rendered and completed; you cannot use it while rendering the view.. You can, however, store the value in a hidden field, put this hidden field in a form, and process it during a post operation. Or, send it to the server via an AJAX callback.
Related
I have a pretty basic, but probably complicated question.
I am using ReactJS.net to render react components server side. I have a typeahead component which I use multiple times throughout my site. One of the properties it expects is a javascript filter function.
I don't want to have to create a seperate component for each instance of the typeahead, but would like to pass in a javascript function as a property so that I can reuse the component throughout the site.
For example, to render a component on the server I would do the following. The second parameter is the properties argment
#Html.React("Components.WorkSiteTypeahead", new { filterFn = model.SomeFunction })
Now as ReactJS.net expects native c# objects (string, array, list, etc), I don't see any straight forward way to pass in a Javascript function. Any ideas on how would I go about telling my MVC5 view to render my function not as a string? My first instinct is that there might be some sort of Javascript Raw type I am not aware of, but haven't been able to find it.
As I suspected, at least one way to go about this is to use Newtonsoft's JRAW Type.
#Html.React("Components.WorkSiteTypeahead", new { filterFn = JRaw("function(){//do stuff } "})
Is there a way to populate anonymous type properties (route arguments) in Html Helpers like Html.ActionLink or Url.Action with data.
Example.
Create link like this:
Anchor Text
... and populate propertyValue with data extracted from current state of DOM (using Javascript).
I know there's a lot of ways that I can get that logic to work (ex. using form data and passing it to controller) but I'm just curious if a provided scenario is possible.
populate propertyValue with data extracted from current state of DOM (using Javascript)
No.
C# runs on the server, JavaScript runs on the client. You can't use JavaScript on the client to modify code which already ran on the server. You can use JavaScript to modify the markup which gets emitted to the client, and the first step in that would be to examine what that markup actually is. (In this case it looks like you'd be modifying a URL, which may involve some interesting string parsing in the JavaScript code.)
But no, JavaScript can't affect your calls to HTML Helpers.
I have a function that I'd like to run when the page loads, so either in document.ready or pageLoad.
Using jquery, I'll trigger the function using its class name
In document.ready
var span = $('.linkify');
span.html(textToLinks(span.html()));
Elsewhere
function textToLinks(text) {
var exp = /(my text)/ig;
return text.replace(exp, "<a class='link' href='http://www.bbc.co.uk' target='_blank' >$1</a>");
}
Now this works with the simple test data, but I need to now work out how to expand the functionality.
I have a list of terms in my c# app, along with the relevant url. I'm thinking of passing this data as a string, and splitting in, however my javascript knowledge has a lot of holes.
So I suppose I have 3 questions:
How do I get my string into the function when the page is loaded?
Is a string the right type or can I pass some other dictionary object?
How do I iterate through each of the terms passed efficiently?
Thanks in advance.
What you can do is, use JQuery Ajax call to retrieve server side data.
But that would require you to set up service that would be exposed. You could do it in a shortcut way with out setting up the service.
But that would require messy logic.(its a short cut :))
You could create a property in your page which exposes the JSON Data as string. You could read the JSON data in your javascript by following
var data =<% GetData() %>
You can define a ToJson on object to convert the object in to JSON String
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
return serializer.Serialize(obj);
}
public string GetData()
{
return (new {SomeData}).ToJson();
}
Note SomeData is a class containing your data(i.e array of urls) or what ever representation you choose.
Then loop over data to build the dynamic html
#Anand is correct saying that you can use jQuery Ajax to retrieve server-side data.
However, depending on exactly what it is you want to do, you might be able to do it another way.
You can use the .net JavascriptSerializer class to serialize your data to JSON format. JSON is a very good tool to become familiar with if you aren't already familiar with it.
JavascriptSerializer will put your JSON in a string, which you can then put inside a hidden input and read with your Javascript code. This has the advantage that there is no need for a second HTTP request, as would be the case with jQuery Ajax.
If you've got your data in advance when the page is loaded, you can write the JSON directly to the page, then use that javascript object to do whatever you need.
I don't know if you're using MVC or WebForms, but the idea is basically the same:
For example (using JSON.NET to serialize):
<script id="some-data" type="application/json">
<%= JsonConvert.SerializeObject(someDotNetObject) %>
</script>
<script type="text/javascript">
var _someJsObject = JSON.parse(document.getElementById("some-data").innerHTML);
</script>
Now _someJsObject is a javascript object representing the data you started with, and you can do whatever you want with it, like looping through an array, etc.
Side note - if you're targeting IE7, you'll need to use something like json2.js to get the JSON parsing.
Another possible way of doing this is to write the javascript function at page load in your C# code. This will then be added to the page when it is rendered and can be executed by the jQuery on document.ready(); or any other function / event.
Example code :
string FunctionStr = "<script type=\"text\javascript\">function textToLinks(text) {" +
"var exp = /(my text)/ig;" +
"return text.replace(exp, \"<a class='link' href='http://www.bbc.co.uk' target='_blank' >$1</a>\");" +
"}</script>";
this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Some JS Function", FunctionStr);
The answers from Anand and Daniel may better suit your desired approach but this is a 3rd option if you desire one.
You can do this way :
Declare public member into your C# class on code behind
public string mystring;
Initiate it in Init or Load Event
And write that on your js function
var exp = '<%=mystring %>';
It should work for string. For Dictionnary, you may try to do Ajax
Heading
I want to pass some variables from one page to another but I don't want them to appear in the URL. When I use a form to post the an ActionResult it works fine. However, when I do this
return RedirectToAction("Trackers",new{page = 1, orderby=desc});
I get the URL:
http://examplesite.com/Trackers?page=1&orderby=desc
Is there any way I can get the following URL instead but still pass the page and orderby variables "behind the scenes"?
http://examplesite.com/Trackers
Thanks
TheLorax
I'm not sure it's a good idea to do what you're suggesting, however, you might be able to use the TempData (same place as the ViewData) to save your information before the redirect. I believe that after your next request, anything in the temp data is cleared out.
You could pass a Model object containing the page number and the orderby instead of an anonymous object, and have your view inherit the model class of the object you are passing. Your model object with the page number and orderby then becomes available to the view, without employing a query string
This is not, however, the preferred method of doing this. Your model objects should be reserved for their intended purpose, which is passing actual data to your view.
When you use RedirectToAction method the browser will recieve an http redirect response from the server and then will do a GET request to the new URL.
I think there is no way to make the browser make a POST request when redirecting.
Also it is better to pass these variables through the query string in order for the user to be able to bookmark the page.
In our new product we have a few data entry fields that require you to search for the correct value to place in this field.
When you enter this data entry field I would like to provide a search option via something on the view (perhaps an Ajax implementation) and have it allow searching of the database for the value, but when the result returns I want to keep the existing values in place for other fields not affected by the search.
But I have no idea how to do this with MVC. Does anyone have any suggestions on how this should be done?
Write your data entry page in the
usual way for an ASP.NET MVC view.
Get it working without the Ajax
(e.g., submit works correctly when
you just type in the values, without
auto complete).
Write the prototype for a JavaScript method you'll called when the user performs a certain action (e.g. presses a key inside of a certain control). But this inside a script tag in your aspx page. Unfortunately, stack overflow seems to "sanitize" script tags in my example, so I can't demonstrate that part. But you're JavaScript prototype will look something like this:
function startAutoComplete() {
}
Now hook up the event handlers on the user interface control. You need to call the function you've just prototyped an appropriate event handlers for your application. From your description, it sounds like you might want to use onkeydown, but there are lots of events to choose from. You probably need to handle more than one event, as appropriate for your application.
So far, everything that we've done has been standard aspx and JavaScript. In this step, we'll do the only part of the whole process which is really different for ASP.NET MVC. You need to add an action to your controller which will be called (indirectly) by the JavaScript prototype you've just written. The action should accept appropriate input (e.g., a string representing the text from control, or something like that, as appropriate for your application) and return its results in JSON format. I'm going to show a really simple example here; feel free to substitute more complex code in your real application.
public ActionResult GetSuggestions(string searchText)
{
return Json(new {SearchText = searchText});
}
This example just returns a JavaScript object containing one property, which contains the value passed to the function. Like you said, you can write something more useful for your application.
Now you need to call this function in JavaScript. The URI will look something like:
http://localhost/mycontroller/GetSuggestions?searchText=Foo
It is possible to make Ajax calls without a JavaScript library, but much easier if you use jQuery or some other library which handles cross-browser compatibility issues for you. Since I happen to like jQuery, I'll demonstrate that. Let's update the startAutoComplete method we prototyped earlier:
function startAutoComplete() {
var searchText = $("#myeditorid").text();
$.getJSON("/mycontroller/GetSuggestions?searchText=" + searchText,
null,
autoCompleteResponse);
}
The first line uses jQuery to get the text in the control with the ID myeditorid. We'll pass this to the ASP.NET MVC action as the searchText argument, by appending it as a query string parameter.
The next line, which starts with $.getJSON calls a jQuery function which makes an Ajax call to the URI you specify. We pass an argument, autoCompleteResponse, which is the name of a JavaScript method to be called if the response from the Ajax call is successful. Now we have to write autoCompleteResponse.
function autoCompleteResponse(data) {
if (data.SearchText)
{
$("#myeditorid").text(data.SearchText);
}
}
This says, "If the data returned has a SearchText property, set the text of the control to that value." Again, do whatever is appropriate for your application with the data returned.