如何使用Javascript扩展formdata并将其发布到Controller

时间:2015-09-30 15:57:10

标签: javascript asp.net-mvc asp.net-mvc-4 post

如何以某种方式使用变量扩展Javascript中的formdata,以便在我的控制器POST操作中可用。

所以我想做的是,添加一个变量更新(这是一个bool)并将我的formdata发送给控制器。

这是我的.js文件的代码&控制器代码

    bootbox.confirm("Are you sure you want to override this Quotation?", function (result) {
        if (result === null) {
           //do nothing
        } else if (result) {
           if (!$form[0].checkValidity()) {
               return false;
           }

           var btn = $('#saveQuotationForm');
           btn.attr('onclick', '');
           btn.attr('class', 'glyphicon glyphicon-floppy-save');
           btn.text('Saving...');

           var formurl = $form.attr('action');
           var formdata = $form.serialize();

           console.log(formurl + " =formurl");
           console.log(formdata + " =formdata");

           //tricky part, i want to do something like this:
           //var update = new boolean(false);
           //formdata.append(update, true); --> but this is obviously not the way to go :), anyone got idea's?**

           $.post(formurl, formdata, function (data) {
                if (data && data.State === 'success') {
                    btn.attr('class', 'glyphicon glyphicon-floppy-saved');
                    btn.text('Saved');
                    $('#placeholderAlert').append('<div class="alert alert-success" role="alert"><strong>Saved</strong> ' + data.Message + '</div>');
                } else {
                    btn.attr('class', 'glyphicon glyphicon-floppy-remove');
                    btn.text('Saving failed');
                }
          });
       }
  });




    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonNetResult Products_Quotation_Save(vmProducts_Quotation_Save quotation)
    {
        quotation.DateCreated = DateTime.Now;
        QuotationCache.Instance.SaveQuotation(GetClientCode(HttpContext), GetUserName(HttpContext), quotation, MuseContext);
        return JsonNet(new { State = "success", Message = "Quotation '" + quotation.Name + "' has been saved with reference " + quotation.ShortCode + ". <a href=" + Url.Action(RouteItemAction.ResaPlus_Quotations) + " class=\"alert-link\">Go to overview</a>" });
    }

修改 这确实是另一个问题的重复,为此道歉。我通过这里提供的答案之一修正了它:jquery form.serialize and other parameters

所以我创建了一个变量并用$ .param添加它,然后在我的控制器中我可以访问该参数。

var update = { 'update': true };
var formurl = $form.attr('action');
var formdata = $form.serialize() + '&' + $.param(update);

$.post(formurl, formdata, function (data) {

});

[HttpPost]
[ValidateAntiForgeryToken]
public JsonNetResult Products_Quotation_Save(vmProducts_Quotation_Save quotation, bool update)
{
}

1 个答案:

答案 0 :(得分:0)

您可以使用serializeArray()创建可更新的对象。 http://api.jquery.com/serializeArray/

var formdata = $form.serializeArray();
formdata.push({name: 'update', value: true});

$.post(formurl, formdata, function (data)