c# - 从部分 View 单击按钮重定向到父操作方法

标签 c# ajax asp.net-mvc asp.net-mvc-3

我的应用程序中有一个“父 View ” View ,我正在使用@Html.BeginForm 和一个提交按钮来保存父 View 的数据。我在父 View 中也有一个局部 View ,我试图从局部 View 调用 ajax 方法(使用 jQuery),但每次它都会将我重定向到父表单的操作方法。

Parent View
@using (Html.BeginForm("Test1", "Home", new { id = 1 }, FormMethod.Get))
{
    @Html.Partial("TestPartial", Model)
    <div>
        <input id="Button1" type="submit" value="Parent" />
    </div>
}

Partial View
<script>
function onClientClick() {
    $.ajax({
        url: "/Home/Test2",
        type: "GET",
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ ID: 1 }),
        cache: false,
        success: function (data) {
            alert('Success');
        },
        error: function (err, result) {
            alert("Error" + err.responseText);
        }
    });
}
</script>
<div>
<input type="submit" name="submit" onclick="onClientClick()" value="Submit" />
</div>

每次我尝试从局部 View 调用/Home/Test2 时,它都会将我重定向到/Home/Test1(父表单的操作)

最佳答案

问题出在这一行:

<input type="submit" name="submit" onclick="onClientClick()" value="Submit" />

类型是 submit 因此它提交表单并将您重定向到父级中的操作。

在您的局部 View 中有一个常规的按钮而不是提交按钮来请求AJAX内容:

<input type="button" onclick="onClientClick()" value="Ajax Call" />

您也可以返回 false,但我相信使用标准的 button 而不是 submit 更适合这种情况。

关于c# - 从部分 View 单击按钮重定向到父操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15636251/

相关文章:

c# - 排序文件数组以重命名

jQuery 和 AJAX?

c# - 更新页面而不刷新它

c# - 类库代码中的url.Content类型方法

c# - Asp.net 身份 我可以编写什么 linq 查询来返回具有其角色的所有用户(包括没有角色的用户)?

c# - HTML 中的嵌入图像未出现在 Outlook 渲染器中

c# - Unix 时间戳(以秒为单位)到 C# DateTime 不是 UTC

c# - 为什么通过 google api 进行的 google 搜索会返回与网页中的搜索不同的结果?

ajax - 当 AjaxFileUpload 触发 UploadComplete 事件时访问其他控件值

jquery - 如果 JSON 对象中有空格,则会出现语法错误。如何逃离太空?