简体   繁体   中英

Get value of a query string from asp.net mvc controller action to <script type=“text/javascript”>

I am passing a query string with name "RowTobeHighLighted" from my Asp.net mvc action result. What I have to do is, I have to get the query string value from that controller action to a script of type text/javascript. I have tried to use simple Request.Querystring() under javascript. But that is not working.

Is it possible to get the querystring value from controller action.Or, is it possible to get the value of viewdata under <script type="text/javascript"> tag.

Well no, Request.QueryString won't work, because it's server side only.

You have a few options

  • You could use Request.QueryString to embed the value in a script

    var myValue = <% = HttpUtilityRequest.HtmlEncode(QueryString["myValue"]") %>

  • You could either pass the query string value as view data to the view and then use it in your javascript like so

    var myValue = <% HttpUtilityRequest.HtmlEncode(ViewData["myValue"]) %>

  • Or you could look at the query string in javascript

    var qs = new Querystring() var myValue = qs.get("myValue")

Of course with all of these you should watch for Cross Site Scripting attacks.

On the client side: use the Querystring .
On the server side: (provide value to JS):

<%= "var RowTobeHighLightedUrl = '" + Request.QueryString["RowTobeHighLighted"] + "';"%>

If the RowTobeHighLighted should be JavaScript Escape (NOT HtmlENcode!).

Use TempData for this sort of temporary message.

In your controller:

TempData["RowToHighlight"] = rowNumber;

And then in the view:

<% foreach (var row in Model) { %>
<tr>
    <td id="row_<%= row.id %>"<%= (row.id == (int)TempData["RowToHighlight"]) ? " class="highlighted" : "" %>>my row</td>
</tr>
<% } %>

And then if you were using jQuery for example to fade out or whatever (inside your of jQuery document.ready):

<% if (TempData["RoToHighlight"] != null) { %>
$("#row_<%= (int)TempData["RowToHighlight"] %>").fadeOut();
<% } %>

Of course, be sure to use any necessary escaping and encoding etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM