【问题标题】:Send temp data from View to Controller将临时数据从视图发送到控制器
【发布时间】:2019-08-12 19:40:18
【问题描述】:

我的 View Jquery 部分中有以下代码:

$('#btnContinue').click(function () {                  

     var createFormName = $("#createFormName");
     createFormName.submit();
}

我喜欢将临时数据从视图发送到控制器,因为我需要根据临时数据值在控制器的操作结果中重定向用户。有没有办法将临时数据从视图发送到控制器的操作结果?

【问题讨论】:

  • 我真的看不出这样做的理由,因为我认为您只想添加一个带有该值的隐藏表单字段并将其与表单提交后一起发送,但您可能会变老school 并在 js 中设置一个 cookie 并在 http 上下文中从控制器的方法中检索它。无论如何,这就是临时数据从服务器到后端的客户端的方式。

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


【解决方案1】:

让我们提供 2 种通过简单示例展示的方法:

最快的方法是通过查询字符串发送。像这样:

    public ActionResult Index()
    {
        TempData["message"] = "Hi";

        return View();
    }

    [HttpGet]
    public ActionResult About(string str1, string str2) { . . . }

然后,在您的索引视图中:

@{
     string str = TempData["message"].ToString();                            
     @Html.ActionLink("Go to About View", "About", new  { str1 =  @str, str2="some text"})
}

另一方面,您可以将数据发布到控制器,而不是通过查询字符串发送; 假设我们在这里有一个简单的视图模型:

public class DoubleStr_ViewModel
{
    public string  str1 { get; set; }
    public string  str2 { get; set; }
}

然后在控制器内部:

    public ActionResult About()
    {
        TempData["message"] = "Hi";            
        return View(new DoubliStr_ViewModel());
    }

    [HttpPost]
    public ActionResult About(DoubleStr_ViewModel input)
    {
        return View();
    }

现在,在 About 视图中:

@using Your.Path.To.ViewModels
@model  DoubleStr_ViewModel

<input type="hidden" value="@TempData["message"].ToString()" id="tmpHidden" />

<form method="post">
    @Html.HiddenFor(x => x.str1)
    @Html.TextBoxFor(x => x.str2)
    <button type="submit">SUBMIT</button>
</form>



@section scripts{
    <script>

        $('form').submit(function () {

            $('input#str1').val($('input#tmpHidden').val());
        });
    </script>
    }

在您的情况下,要触发表单提交,您将拥有:

$('#btnContinue').click(function () {                  

     // first, fill the hidden value(s) into your model
     $('input#str1').val($('input#tmpHidden').val());

     var createFormName = $("#createFormName");          
     createFormName.submit();
}

希望,这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2015-08-06
    相关资源
    最近更新 更多