【问题标题】:Passing URL parameter and a form data together一起传递 URL 参数和表单数据
【发布时间】:2010-04-07 02:29:59
【问题描述】:

我有以下网址:

http://localhost:49970/Messages/Index/9999

在视图“索引”处,我有一个表单,我使用 Jquery 将表单数据发布到操作索引(用 [HttpPost] 装饰),如下所示:

查看:

<script type="text/javascript">
    function getMessages() {
        var URL = "Index";
        $.post(
            URL,
            $("form").serialize(),
             function(data) {
                 $('#tabela').html(data);
             }
        );
    }
</script>

 <% using (Html.BeginForm()) {%>

        <%=Html.TextArea("Message") %>

        <input type="button" id="submit" value="Send" onclick="javascript:getMessages();" />

    <% } %>

控制器:

[HttpPost]
public ActionResult Index(FormCollection collection)
{
   //do something...
     return PartialView("SomePartialView", someModel);
}

我的问题:如何在操作索引中获取参数“9999”和表单FormCollection?

PS:对不起我的英语:)

【问题讨论】:

    标签: jquery asp.net-mvc asp.net-mvc-2


    【解决方案1】:

    您需要在路由集合中声明 id。然后,只需在动作中添加一个同名的动词即可。

    public ActionResult Index(int id, string otherPostData...)
    {
       //do something...
         return PartialView("SomePartialView", someModel);
    }
    

    查看此处了解 MVC url 路由如何工作的详细信息:

    http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

    【讨论】:

    • 感谢 Mendy 的快速回答 :) 实际上,我的参数是一个 guid(类似于“08254a2a-7089-46e6-b03d-406a72a34148”)。我尝试像你说的那样声明方法: public ActionResult Index(Guid?id, string Message) { //id is null //Message 没问题(有我输入的值) return PartialView("SomePartialView", someModel) ;如果我更改可为空的 Guid?只有 Guid,当我点击按钮时,什么也没有发生......
    【解决方案2】:

    一种简单的方法是将Id 添加到您的表单值中。

    这应该可以解决问题:

    <% using (Html.BeginForm()) {%>
    
        <%=Html.Hidden("Id") %>
    
        <%=Html.TextArea("Message") %>
    
        <input type="button" id="submit" value="Send" onclick="javascript:getMessages();" />
    
    <% } %>
    

    如果这不起作用,您需要将Id 放入控制器中的ViewData

    另一种方法(可能更简洁)是从表单的 action 属性中获取 jQuery 发布到的 URL。当你这样做的时候,我也会让 js 变得不引人注目。

    HTH,
    查尔斯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-21
      • 2018-02-20
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      相关资源
      最近更新 更多