FormData如何将文件和参数传递给mvc控制器操作

时间:2016-03-23 13:57:55

标签: c# jquery ajax asp.net-mvc

我正在尝试将文件和参数传递给MVC控制器操作。我可以在控制器中获取我的模型,文件,但不能在string CommunId, string CommunContext等控制器中获取我的其他变量,我知道这可能是因为这些false参数,但如果我没有将它设置为{{ 1}}甚至没有调用我的控制器动作。这是我的代码:

false

我的观点

function submitNewCommunication(s, e) {
     // var data = new FormData($(this).serialize()); //tried this one also

        $.ajax({
            url: '@Url.Action("CreateCommunication", "Communications")',
            type: 'POST',
            data: new FormData($('.createCommunicationForm').get(0)),
            processData: false,
            contentType: false,
            success: function (result) {
                alert('test'); 
            }
        });

}

我的MVC控制器:

@using (Html.BeginForm("CreateCommunication", "Communications", new { CommunContext = ViewBag.CommContext, CommunId = ViewBag.CommId }, FormMethod.Post, new { @class = "createCommunicationForm"}))
{
//some code
}

所以文件和模型在这里,但不是这些其他变量,也许有一个简单的解决方案我如何获得它们?感谢您的帮助和您的时间。

1 个答案:

答案 0 :(得分:1)

您可以通过表单中的隐藏字段传递您需要的值:

@using (Html.BeginForm("CreateCommunication", "Communications", FormMethod.Post, new { @class = "createCommunicationForm"}))
{
    <input type="hidden" name="CommunContext" value="@ViewBag.CommContext">
    <input type="hidden" name="CommunId" value="@ViewBag.CommId">
}