简体   繁体   English

发布JSON和提交表单(或重定向)

[英]Post JSON and Submit Form (or redirect)

I'm struggling with how to properly submit a form where I really only need to send the JSON and not the form controls. 我正在努力如何正确提交表单,而实际上我只需要发送JSON而不发送表单控件。 I have a SubmitOrder() javascript function: 我有一个SubmitOrder()JavaScript函数:

function SubmitOrder() {
    var selectedProductsAsJson = JSON.stringify(selectedProducts);
    // This line works...
    $.post('/OrderCheckout/Save', { jsonData: selectedProductsAsJson });
    // ... or this line works...
    $('#productListForm').submit();
    // but not both lines together.
}

What I'm trying to do is send selectedProductsAsJson to my controller, process it, then send the user to a new page. 我想做的是将selectedProductsAsJson发送到控制器,对其进行处理,然后将用户发送到新页面。 The $.post line accomplishes the first two actions, but I don't know how to send the user to a new page after that. $ .post行完成了前两个操作,但此后我不知道如何将用户发送到新页面。

If I just do the .submit() line, the user is redirected to the new page, but the controller doesn't have the json data to process. 如果我只是执行.submit()行,则会将用户重定向到新页面,但是控制器没有要处理的json数据。

If I use both lines, the $.post call is asynchronous and the user will end up on the new form before the $.post call completes. 如果我同时使用这两行,则$ .post调用是异步的,并且用户将在$ .post调用完成之前进入新表单。 I read here that I can make the $.post call synchronous, but it seems like I should be able to do all of this with one call to the server. 在这里阅读可以使$ .post调用同步,但是似乎我应该能够通过对服务器的一次调用来完成所有这些操作。 What am I missing to make this happen? 我错过了什么使这种事情发生?

My controller currently looks like this; 我的控制器当前看起来像这样;

public class OrderCheckoutController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public void Save(string jsonData)
    {
        List<Product> selectedProducts = new JavaScriptSerializer().Deserialize<List<Product>>(jsonData);
        decimal totalPrice = selectedProducts.Sum(x => x.Price);
        ViewBag.SaleTotal = totalPrice;
    }
}

you can use the success callback function (third parameter) of $.post 您可以使用$ .post的成功回调函数(第三个参数)

The "success url" can be hard coded or come from your POST ( Save ) action (which is actually void, but could be a JsonResult) “成功url”可以是硬编码的,也可以来自您的POST( Save )操作(实际上是无效的,但可以是JsonResult)

$.post('/OrderCheckout/Save', 
       { jsonData: selectedProductsAsJson }, 
        function() {
          $('#productListForm').submit();
        }
      );
public ActionResult Save(string jsonData)
{
    List<Product> selectedProducts = new JavaScriptSerializer().Deserialize<List<Product>>(jsonData);
    decimal totalPrice = selectedProducts.Sum(x => x.Price);
    ViewBag.SaleTotal = totalPrice;
    return RedirectToAction("Index");
}

OR 要么

$.post('/OrderCheckout/Save', { jsonData: selectedProductsAsJson }, 
        function() {
          $('#productListForm').submit();
        }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM