c# - ASP MVC 表单调用特定操作而不是重定向但更新原始页面

标签 c# jquery asp.net asp.net-mvc-3 forms

我正在为一个项目使用 ASP.net MVC 3,现在我对它有了更多的了解,但也试图了解它与我使用了很长时间的 WebForms 世界之间的区别。以前在 WebForms 中,您只需将字段放在那里,添加一个按钮,创建一个事件,然后通过回发处理您需要的任何事情。

例如,我有一个显示错误详细信息的简单 View 。我想将有关此错误的一些信息推送到我们的问题跟踪器的 API。让我们只说错误的主题和内容。我会在 HTML 中做类似的事情:

<form action="@Url.Action("Send")" method="post">
    <input id="subject" name="subject" type="text" value="@Model.subject" />
    <br />
    <input id="content" name="content" type="text" value="@Model.content" />
    <br />
    <input type="submit" value="Send" />
</form>

我发现命名我的输入 ID 以匹配我的 Controller 中的参数名称会让我传递这些参数。这类似于您在 Scott Guthrie 的这篇旧帖子中看到的内容.

首先,我想在我的错误 Controller 中调用“发送”操作,而不是在我的详细信息 Controller 中调用。这实际上调用了我的“发送”操作,但随后重定向到 localhost/Errors/Send,这是我不希望的。

我希望能够提交此表单,该表单调用和操作并使用远程 API 进行工作,然后在当前页面上更新一条消息,说明错误已转移。

问题提交给错误跟踪器后,我该如何在原始页面上显示一个 DIV,将内容传回给它(例如,问题跟踪器中问题的链接)?

更新:这是我在我的 Controller 中所做的:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/redmine/issues.json");
request.Credentials = new NetworkCredential("username", "password");
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";

using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write("'issue': { " +
                      "'project_id': 'project', " +
                      "'subject': 'Test issue'" +
                      "}");
}

WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
string json = "";

using (StreamReader reader = new StreamReader(stream))
{
    json = reader.ReadToEnd();
}

另外,这就是我在做的事情(在 Phillip 的帮助下进行了简化)

@model webapp.Models.app_errors

<script type="text/javascript">
 function SendErrors() {    

           alert(@Model); // here I get a 'webapp undefined error'
           alert(Model); // Model is undefined. If I reference @Model.App_name or another value anywhere, works fine in rest of view

        $.ajax({
            type: 'POST', //(probably)
            url: '../SendToRedmine',
            cache: false, //(probably)
            dataType: 'json', //(probably)
            data: @Model,
            success: function(result)
            {
                alert("The error has been transferred");
                //you can also update your divs here with the `result` object, which contains whatever your method returns
            }
            });
    }
</script>

<input type="button" onclick='SendErrors()'/>

最佳答案

为回答您的第一个问题,请尝试重载 Url.Action:

Url.Action("ActionName","ControllerName")

你的第二个问题:你会想通过 AJAX 来完成。

基本上,第一次加载页面时,将要显示的内容返回到屏幕。然后,具有这种形式的 ajax 函数:

<script type="text/javascript">
    function SendErrorsOrWhatever()
    {
        dummy = 'error: myError, someOtherProperty = property';  //this of course assumes that 'myError' and 'property' exist
        $.ajax({
        type: 'GET', //i changed this because it actually probably better suits the nature of your request
        url: '../Details/Send',
        cache: false, //(probably)
        dataType: 'json', //(probably)
        data: dummy,  //json object with any data you might want to use
        success: function(result)
        {
            alert("The error has been transferred");
            //you can also update your divs here with the `result` object, which contains whatever your method returns
        }
        });
    }
</script>

需要注意的几点: 1) url 自动附加到包含来自 data 的数据。 2) 您的操作方法现在需要接受一个参数。有很多方法可以解决这个问题。我在下面的代码中添加了一个示例,说明您的操作方法可能是什么样子。

然后按钮的 onclick 事件将调用该函数,如下所示:

<input type="button" onclick='SendErrorsOrWhatever()'/>

这里发生的是,当您的按钮被点击时,Ajax 将异步地(默认情况下)点击您的操作方法,并且您的操作方法将对错误做任何它需要做的事情,然后当它完成时,success 回调将被命中。

编辑:现在,您的操作可能看起来像这样:

[AcceptVerbs(HTTP.Get)]
public static Error GetErrors(Error error)
{
    //do all your processing stuff
}

现在,假设 JSon 对象 dummy 具有与 Error 类相同的字段。如果是这样,MVC 将对其进行自动数据绑定(bind)。您也可以为参数使用更通用的 FormCollection。实际上,您可以使用任何您想要的东西,但您需要将任何您想要的东西包装在 JSON 对象中。

编辑——对于你的最后一个问题,这应该有效:

将以下扩展方法添加到您的应用中:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

或者如果你愿意,你可以只添加一个 ToJson() 方法到你的模型类,然后:

var model = @Model.ToJson();

在 ajax 调用之前的 js 中。然后将 model 变量用于您的 data 参数。

关于c# - ASP MVC 表单调用特定操作而不是重定向但更新原始页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10761043/

相关文章:

C# MVVM 如何将命令添加到 TextBlock

javascript - 使用jquery滚动底部div

javascript - 在两个方向上动态加载用户控件

c# - 如何使用 Asp.Net C# 更改 GridView 中列的顺序

c# - 如何在 C# 中动态更改 td 的 colspan?

c# - 在 MVC 4 网站上持续运行后台进程

c# - 实现扩展方法

c# - LINQ如何动态使用多个ThenBy?

php - php循环中的ajax在按钮单击时执行操作

javascript - 动态构建包含 html 的 ajax 调用的数据字符串