【问题标题】:string parameter null in controller action控制器操作中的字符串参数 null
【发布时间】:2013-06-20 06:41:46
【问题描述】:

我正在尝试使用 ASP.NET MVC 部分视图上传文件。

**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 参数始终为空。上面的代码有什么问题?

【问题讨论】:

  • 您不能使用 ajax 发布文件。您应该使用 ajax 文件上传插件...
  • @ChamikaSandamal 它只是一个具有静态值的隐藏字段。我没有发布代码
  • 你是否在同一个表单中定义了selID?
  • Jquery 代码在哪里。如果它在外面,那么它将无法正常工作。在表单中定义 selID 然后它就会起作用

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


【解决方案1】:

方法 - 1

Ajax FileUpload 插件在某处上传文件,并通过 响应回调,仅此而已。

  • 它不依赖于特定的HTML,只需给它一个&lt;input type="file"&gt;
  • 它不需要您的服务器以任何特定方式响应
  • 无论您使用了多少文件,也不管它们在页面上的什么位置

-- 尽量少用--

$('#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。

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

我有四个问题。

问题 - 1

如果使用FormCollection...强制类型转换Primitive 类型值是不必要的,因为在获取System.Collections.Specialized.NameValueCollection 的特定索引条目时,返回的值是类型细绳。这种情况在强类型View-Models的情况下不会出现。

问题 - 2

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

问题 - 3

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

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

问题 - 4

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

方法 - 3

Uploadify - Please check here

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

【讨论】:

    【解决方案2】:

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

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

    在函数开始处使用preventDefault 方法来阻止表单被发布:

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

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

    【讨论】:

      【解决方案3】:

      如果您想实现类似 AJAX 的文件发布,您必须使用 3rd 方 AJAX 插件、Flash 上传器或其他任何可以在 Web 浏览器下访问文件系统的工具。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-02
        • 1970-01-01
        • 1970-01-01
        • 2015-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多