简体   繁体   中英

How can I pass parameters to a new page from Javascript?

I have the following code:

$('#CreateButton').click(function (event) {
 var datastoreValue = $("#SelectedDatastore").val();
 window.location = "/Q/Create?datastore=" + datastoreValue;
});

It works good but I would like to have the datastore=XYZ hidden from my user. Is there another way that I can pass this information so I would be able to read it in my MVC controller. Currently I read it like this:

    public ActionResult Create(string datastore)
    {

When inside this method the value of datastore is available to me.

Surround you code with a form tag with a method set to POST. Also add HttpPost attribute above your Create action. This will post the data to your action without client seeing the query string value. If you are posting to another action that specify that in your action attribute inside form. For example,

<% using (Html.BeginForm("Create", "MyController", null, FormMethod.Post)) { %>
<%: Html.Label("Data store value: ")%>
<%: Html.TextBox("datastore") %>
<input type="submit" value="Submit" />
<% } %>

Your Create action will pick this up and do the rest.

Hope this helps,

Huske

You could put the datastore value in a cookie to hide it from the user, though cookies are best used for settings that you want to last awhile, not settings that are meant just for one page.

Or, you could use a Post and put the create information in a hidden form and submit that.

Or, you could use an Ajax call to issue the create and then change the page yourself afterwards.

Otherwise, the query parameter like you are using is a standard way of specifying page-level parameters for a new page.

If you stay on the same website, you can post your data to your controller; it will pick up the data from the post collection and your url won't display the query string parameters.

Just wrap your form with the control whose id is SelectedDataStore in atag with the action set to your url and the method set to post

Here is one quick example with a submit button:

<FORM action="/Q/Create" method="post">
    <INPUT id="SelectedDataStore" />
<INPUT type="submit" value="Send">
 </FORM>

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