控制器操作中的字符串参数null

时间:2013-06-20 06:41:46

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

我正在尝试使用ASP.NET MVC Partial view上传文件。

**Partial view:**

@using (Html.BeginForm("FileUpload", "Item", FormMethod.Post, new { enctype = "multipart/form-data", id="frmUp" }))
{
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
}

主要表格:

<div id="uploadDiv" class="divSettings" align="left">        
    @Html.Partial("FileUpload")
</div>

在我的主要表格中,我有以下代码。

$("#frmUp").submit(function () {
    var serviceURL = '/Item/FileUpload/';
    var id = $("#selID").val();
    alert(id);
    $.ajax({
        type: "POST",
        url: serviceURL,
        data: { id: id },
        dataType: "json",
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {        
    }

    function errorFunc() {
    }
});

控制器:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file, string id, FormCollection formCollection)
{
    //here id parameter is null and i get the file parameter values
    return PartialView();
}

在我的控制器中,id参数始终为null。上面的代码是什么问题?

3 个答案:

答案 0 :(得分:0)

您尚未停止表单的正常操作,因此您将照常发布并发送AJAX请求。

这是表单的常规发布,为null提供id值,因为表单中没有任何具有该名称的字段。

使用函数开头的preventDefault方法停止发布表单:

$("#frmUp").submit(function (e) {
  e.preventDefault();
  ...

这将使AJAX请求到达服务器而不是常规发布表单,但是file参数将始终为null,因为您无法使用AJAX发布文件。

答案 1 :(得分:0)

如果您想要实现类似AJAX的文件发布,您必须使用第三方AJAX插件,Flash上​​传器或其他任何可以在Web浏览器下访问文件系统的内容。

但是,如果您不想混合技术,则可以始终使用隐藏的iframe方法。事实上,我一直在我最近工作的项目中使用这种方法,它工作得非常好!

以下是一些有用的资源:
http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/
Jquery File Upload Hidden IFrame

答案 2 :(得分:0)

方法 - 1

Ajax FileUpload 插件上传文件,然后传递 响应回调,没有别的。

  • 它不依赖于特定的HTML,只需给它一个<input type="file">
  • 它不需要您的服务器以任何特定方式响应
  • 您使用的文件数量或页面上的位置无关紧要

- 尽量少用 -

$('#one-specific-file').ajaxfileupload({
  'action': '/upload.php'
});

- 或者与 -

一样多
$('input[type="file"]').ajaxfileupload({
    'action': '/upload.php',
    'params': {
    'extra': 'info'
    },
    'onComplete': function(response) {
    console.log('custom handler for file:');
    alert(JSON.stringify(response));
    },
    'onStart': function() {
    if(weWantedTo) return false; // cancels upload
    },
    'onCancel': function() {
    console.log('no file selected');
    }
});

接近-2

@model FileUpload
@using (Ajax.BeginForm("YourActionMethod", "ControllerName", new AjaxOptions
    {
        HttpMethod = "POST"
    }, new { enctype = "multipart/form-data", id = "frmUp" }))
{
    <input type="file" accept="image/*" name="FileInfo" value="File to Upload" />
    <input type="submit" name="Submit" value="Submit" />
}


[HttpPost]
public ActionResult YourActionMethod(UploadFileModel fileModel)
{
    return View();
}

public class UploadFileModel
{
    public HttpPostedFileBase FileInfo { get; set; }
}

如果你注意上面的代码,我正在使用Ajax.BeginForm。除此之外,我建议使用View-Models将数据传回给你Action Method而不是FormCollection。

enter image description here

为什么要查看模型而不是FormCollection?

我有四个问题。

问题 - 1

如果正在使用FormCollection ...必须非必要地输入Primitive类型值,因为在获取System.Collections.Specialized.NameValueCollection的特定索引条目时,返回的值是String类型。在强类型View-Models

的情况下,不会出现这种情况

问题 - 2

当您提交表单并转到Post操作方法,并且Action方法中存在View-Model as Parameter时,您可以将发布的值发送回View。否则,再次编写代码以通过TempData/ViewData/ViewBag

发回

问题 - 3

在准备单元测试用例时,您将再次遇到 Issue-1 中提到的相同问题。当代码以下列方式编写时,这是一个非常大的问题。由于单元测试用例中没有请求。

public ActionResult MyActionResult()
{
    String value = Request.Form["Key"];
    return View();
}

问题 - 4

我们Data Annotations可以在View ModelCustom Validations中实施。

<强> enter image description here

方法 - 3

<强> Uploadify - Please check here

注意 - 为了检索Post Action Method控件中的已发布值,它 必须将控件保留在表单标记内。同样,您的Hidden Fields也应该位于Form标记内,以便在Post操作方法

中获取它的值