简体   繁体   English

将类型文件中的数据发送到ASP.NET MVC中的控制器

[英]Sending data inside the type file to the controller in ASP.NET MVC

I want to sending a photo for posting blog! 我要发送照片以发布博客!

I have defined two properties in my model. 我在模型中定义了两个属性。 One for the name of the photo to be stored in the database and And another one to get the file and save to the server (in Resources Folder). 一个用于存储要存储在数据库中的照片名称,另一个用于获取文件并将其保存到服务器(在资源文件夹中)。

this is my model code : 这是我的模型代码:

[DataType(DataType.Upload)]
public HttpPostedFileBase File { get; set; }

public string BlogImage { get; set; }

this is my HTML code : 这是我的HTML代码:

<div class="form-group col-sm-8">
                    <label for="BlogImage">Blog Image</label>
                    <input type="file" class="form-control" id="BlogImage">
                </div>

I want to send the file to the server with AJAX. 我想使用AJAX将文件发送到服务器。

 var myAdminBlog = {
    BlogImage: $("#BlogImage").val(),
    File: $("#BlogImage").val()
};

$.ajax({
    url: 'AddPostBlog',
    data: JSON.stringify(myAdminBlog),
    type: "POST",
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function (data) {
        alert(data);
    },
    error: function (errormessage) {
        alert(errormessage);
    }
});

This is my Ajax Code. 这是我的Ajax代码。

Finally, you can see the controller code. 最后,您可以看到控制器代码。

 public JsonResult AddPostBlog(csAdminBlog myAdminBlog)
    { 
       int UploadMessage = UploadImage(myAdminBlog);
       return Json("Post Sended", JsonRequestBehavior.AllowGet);

    }

My problem is exactly that I do not know how to get the file from javascript. 我的问题恰恰是我不知道如何从javascript获取文件。

I tried to use the $("#BlogImage").val() method, but failed. 我尝试使用$(“#BlogImage”)。val()方法,但失败了。

Note: All codes work well and all information is sent to the controller , Only the item that is not sent is the File option 注意:所有代码都可以正常工作,所有信息都将发送到控制器,只有未发送的项目是“文件”选项

If it is not necessary to be in jQuery then you can use document.getElementById(BlogImage).files[0] 如果不需要使用jQuery,则可以使用document.getElementById(BlogImage).files[0]

Create Class like this 这样创建类

Public Class UploadFile
{
[DataType(DataType.Upload)]
public HttpPostedFileBase File { get; set; }

public string BlogImage { get; set; }

}

Then in javascript 然后在JavaScript

 var UploadFile= new Object();
 UploadFile.BlogImage = $("#BlogImage").val();
 UploadFile.File = document.getElementById(BlogImage).files[0];

$.ajax({
   url: 'AddPostBlog',
   data: JSON.stringify({uploadFile:UploadFile}),
   type: "POST",
   contentType: "application/json;charset=utf-8",
   dataType: "json",
   success: function (data) {
      alert(data);
   },
   error: function (errormessage) {
      alert(errormessage);
   }

}); });

And In Controller Method 和在控制器方法

 public JsonResult AddPostBlog(UploadFile uploadFile)
 { 
  //Your Code

}

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

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