本文介绍了ASP.NET MVC路由,Html.BeginForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <%使用(Html.BeginForm(SearchByZip,经销商,新{邮编=},FormMethod.Get))
  {%GT;
< D​​IV>
<输入类型=文本级=padLeftNAME =邮编ID =ZIP的风格=宽度:200像素/>
<输入类型=提交级=btnFind值=搜索/>
< / DIV>
<%}%GT;

这给我的网址的经销商/ SearchByZip?邮编= 12345
我想这个结束了起来:经销商/ ZIP / 12345
(如果我手动在网址栏中输入经销商/ ZIP / 12345返回正确的结果,但是当我点击提交以经销商/ SearchByZip?邮编= 12345来了
我缺少什么?

  routes.MapRoute(
            DealerSearchByZip
            搜索/ ZIP / {}拉链,
            新{控制器=经销商,行动=SearchByZip,邮编=}
         );


解决方案

这是因为发生了拉链是你的形式,而不是路由数据的输入字段。所以,当页面呈现它创建使用的缺​​省路由的URL(DealerSearchByZip路线不匹配,因为邮编并不如路由数据给出)。

您可以通过JavaScript实现这一点,通过当拉链字段更新表单上更新行动属性。
使用jQuery例如:

  $('输入[名称=拉链]')。更新(函数(){
    $('形式')ATTR('行动','经销商/ ZIP /'+ $(本).VAL());
});

或者,由于Zip是你担心的唯一价值,

  $(形式)。递交(函数(){
    。window.location的='经销商/ ZIP /'+ $('输入[名称=拉链]')VAL();
});
<% using (Html.BeginForm("SearchByZip", "Dealer", new { zip = ""}, FormMethod.Get))
  { %>
<div>
<input type="text" class="padLeft" name="Zip" id="Zip" style="width: 200px" />
<input type="submit" class="btnFind" value="Find" />
</div>
<% } %>

This gives me the url "Dealer/SearchByZip?Zip=12345"I would like to end up with this: "Dealer/Zip/12345"(if I manually type in the url "Dealer/Zip/12345" it returns the right results, but when I click in submit it comes up with "Dealer/SearchByZip?Zip=12345"What am I missing?

routes.MapRoute(
            "DealerSearchByZip",
            "Search/Zip/{zip}",
            new { Controller = "Dealer", action = "SearchByZip", zip = "" }
         );
解决方案

This is happening because "Zip" is an input field in your form, not route data. So, when the page is rendered it creates a url using the default route ("DealerSearchByZip" route wasn't matched because Zip wasn't given as route data).

You could accomplish this via javascript, by updating the "action" attribute on the form when the "zip" field is updated.Example using jQuery:

$('input[name=Zip]').update(function(){
    $('form').attr('action', 'Dealer/Zip/' + $(this).val());
});

Or, since Zip is the only value you're worried about,

$('form').submit(function(){
    window.location = 'Dealer/Zip/' + $('input[name=Zip]').val();
});

这篇关于ASP.NET MVC路由,Html.BeginForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:05