asp.net mvc强制在表单上获取URL的样式 [英] asp.net mvc force style of get url on form

查看:59
本文介绍了asp.net mvc强制在表单上获取URL的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于搜索用户的简单表格

I have a simple form for searching for a user

<p>Enter a user's id number to search:</p>

<%  using (Html.BeginForm("Search", "UserAdmin", FormMethod.Get)) { %>
        
        <%= Html.TextBox("id") %>
        
        <input type="submit" value="Search" />
<% } %>

我希望此链接转到useradmin/search/{id},但该链接呈现为useradmin/search?id = {id}

I want this link to go to useradmin/search/{id} but the link is rendered as useradmin/search?id={id}

这两个网址都是有效的,并且可以按照我的预期映射到我的操作,我只是认为前者比较整洁,并且希望使用该样式.

Both urls are valid and map to my action as I would expect, I just think the former is neater and want that style to be used.

基于Michael Gattuso的回答,我将此作为可行的解决方案.不优雅,但是可以.

Based on Michael Gattuso's answer I have this as a working solution. Not elegant, but it works.

<p>Enter a user's id number to search:</p>

<%  using (Html.BeginForm("SearchPost", "UserAdmin")) { %>
        
        <%= Html.TextBox("id") %>
        
        <input type="submit" value="Search" />
<% } %>


    public ActionResult Search(string id)
    {
        var result = _Service.SearchForUsers(id);
        return View(result);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SearchPost(string id)
    {
        return RedirectToAction("Search", new { id = id });
    }

推荐答案

这不是MVC问题.使用GET的表单请求将根据您获得的呈现将输入附加到查询字符串中.MVC中没有任何东西可以解决此问题,因为请求没有通过路由引擎.您可以选择POST表单并进行路由,也可以使用javascript.

This isn't an MVC issue. A form request using GET will append the inputs to the query string as per the rendering you get. There is nothing in MVC that would fix this as the request does not go through the routing engine. Your option is either POST the form and route it or use javascript.

更新

要在MVC中执行此操作,请使用POST形式

To do this in MVC use a form POST

<p>Enter a user's id number to search:</p>

<%  using (Html.BeginForm("Search", "UserAdmin", FormMethod.Post)) { %>

        <%= Html.TextBox("id") %>

        <input type="submit" value="Search" />
<% } %>

通过相应的操作:

[AcceptVerb("Post")]
[ActionName("Search")] //I assume your current search action has this same signature so use alias
public ActionResult SearchPost(int id){
  return new ActionResult("Search", new { Id = id });
}

这篇关于asp.net mvc强制在表单上获取URL的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆