简体   繁体   English

MVC表单提交需要带有%20而不是'+'的查询字符串

[英]MVC form submission need query string with %20 not with '+'

I have a search input type in my form. 我的表单中有一个搜索输入类型。 When the form is submitted, the page reloads with query params with + 提交表单后,页面会重新加载带有+的查询参数

So if I search for abc def the query param becomes ?q=abc+def the url becomes https://localhost:44300/Search?q=abc+def 因此,如果我搜索abc def则查询参数变为?q=abc+def ,网址变为https://localhost:44300/Search?q=abc+def

Now this is sent to the webapi as an api call. 现在,它作为api调用发送到webapi。 so then on server side I am replacing the + with space then performing the search on the controller. 所以在服务器端,我用空格替换+ ,然后在控制器上执行搜索。 Now when I search for abc def+efg it becomes abc+def%2Bdef 现在,当我搜索abc def+efg它将变为abc+def%2Bdef

request.Query = request.Query.Replace('+', ' ');
request.Query = HttpUtility.UrlDecode(request.Query);

So on server side I am first replacing the param's + s with a space character then decoding it and finally I get abc def+efg on the controller which is what I was looking for. 因此,在服务器端,我首先用空格字符替换参数的+ ,然后对其进行解码,最后在控制器上得到abc def+efg ,这正是我想要的。

All this could be avoided if on the form submission the url was encoded. 如果在表单提交中对网址进行编码,则可以避免所有这些情况。 so if from beginning the query param was ?q=abc%20def%2Befg I would just need to decode it. 因此,如果从一开始查询参数是?q=abc%20def%2Befg我只需要对其进行解码即可。

How to do that? 怎么做?

Edit 编辑

The page renders first, then a vue component gets the query parameter, and makes a call to api controller with axios. 页面首先呈现,然后vue组件获取查询参数,并使用axios调用api控制器。 /api/search

const searchQuery = this.$router.getQueryParam('q');

this.queryParams.query = searchQuery ? searchQuery : null;

return axios.get(`/api/search`, {
  params: queryParams,
});

If you were submitting a form , the urleconding would be automatically applied. 如果您正在提交form ,则将自动应用该阅览。 Since you are getting and sending the search query without form submission, just apply a javascript function to encode that fetched value: 由于您是在没有提交表单的情况下获取和发送搜索查询的,因此只需应用javascript函数来编码获取的值即可:

this.queryParams.query = searchQuery ? encodeURI(searchQuery): null;

You can do like this. 你可以这样

Uri.EscapeUriString(request.Query) Uri.EscapeUriString(request.Query)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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