【问题标题】:Jquery submit not triggering controller action method correctlyJquery提交未正确触发控制器操作方法
【发布时间】:2015-03-14 22:45:29
【问题描述】:

提交表单时调用了uploadimage操作,但前面有一个id,可能是我的路由配置不对?

它正在提交 managespace/4/uploadimage 呈现的 html 是这样的

<form action="/ManageSpaces/4/UploadImage"

路由配置

routes.MapRoute("ManageSpaces",
            "ManageSpaces/{id}/{action}",
            new { controller = "ManageSpaces"}, //removed action = "overview" from default - this would make it optional, now its mandatory 
            new { id = @"\d+" } //The regular expression \d+ matches one or more integers
            );

jquery

$('#selectedFile').change(function() {
    $('#imageajaxForm').submit();
});

<div id="images">
            @using (Ajax.BeginForm("UploadImage", "ManageSpaces", new { id = Model.SpaceId }, new AjaxOptions
            {
                HttpMethod = "get",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "imageList"
            }, new { id = "imageajaxForm" }))
            {
                @*@Html.TextBoxFor(model => model.TeacherImageFileBase, new { @type = "file", id = "selectedFile", style = "display: none;" })*@
                <input type="file" id="selectedFile" style="display: none;" />
                <input type="button" value="Add Photos" class="btn" id="pictureupload" />
            }
            <div id="imageList">
                @foreach (var image in Model.Images)
                {
                    <h4>this is an image</h4>
                }
            </div>
        </div>

控制器中的动作方法

[HttpGet]
    public ActionResult UploadImage(int id)
    {
        return Json("Saved");
    }

【问题讨论】:

  • 你没有id="imageajaxForm"的控件
  • new { name = "imageajaxForm" } 用 id 试了一下,还是不行
  • 检查你生成的html。 new { id = "imageajaxForm" }Ajax.BeginForm() 的最后一个参数)应该是&lt;form .... id="imageajaxForm" ...&gt;
  • 现在你已经完全改变了问题!您使用new { id = Model.SpaceId } 指定id 路由参数,并将路由定义为ManageSpaces/{id}/{action},这导致action="/ManageSpaces/4/UploadImage"(假设值为SpaceId = 4)。您希望网址看起来如何?

标签: jquery html asp.net-mvc asp.net-ajax


【解决方案1】:

也许我命名表单的方式有问题

是的,现在你有new { name = "imageajaxForm" },但在你的javascript代码中你使用$('#imageajaxForm'),这意味着你应该给你的表单一个id,而不是name

new { id = "imageajaxForm" }

【讨论】:

  • 我将名称更改为 id 并尝试提交到 /ManageSpaces/4/UploadImage。这包括我不想要的 url 中的 id。如何防止这种情况发生?
  • 网址由您的Ajax.BeginForm生成。您在其中包含了 ID:new { id = Model.SpaceId }。并且由于您将路由定义为ManageSpaces/{id}/{action},因此它将生成 BeginForm 方法将遵循此模式。显然您可以删除它,但您的控制器操作将不再起作用,因为它当前需要一个 id 整数参数。因此,您要达到的目标还不是很清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多