ASP.NET MVC Ajax file upload with jquery form plug

2019-03-14 08:23发布

问题:

I use Jquery Ajax Form Plugin to upload file. Codes:

AuthorViewModel

public class AuthorViewModel
{
    public int Id { get; set; }

    [Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
    [Display(Name = "Yazar Adı")]
    public string Name { get; set; }

    [Display(Name = "Kısa Özgeçmiş")]
    public string Description { get; set; }

    [Display(Name = "E-Posta")]
    public string Email { get; set; }

    public string OrginalImageUrl { get; set; }

    public string SmallImageUrl { get; set; }
}

Form

@using (Html.BeginForm("_AddAuthor", "Authors", FormMethod.Post, new { id = "form_author", enctype = "multipart/form-data" }))
{
    <div class="editor-label">
        <input type="file" name="file" id="file" />
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    ...

    <div class="submit-field">
        <input type="submit" value="Ekle" class="button_gray" />
    </div>
}

Script

<script>
$(function () {
    $('#form_author').ajaxForm({
        beforeSubmit: ShowRequest,
        success: SubmitSuccesful,
        error: AjaxError
    });
});

function ShowRequest(formData, jqForm, options) {
    $(".loading_container img").show();
}

function AjaxError() {
    alert("An AJAX error occured.");
}

function SubmitSuccesful(result, statusText) {
    // Veritabanı işlemleri başarılı ise Index sayfasına
    // geri dön, değilse partial-view sayfasını yenile
    if (result.url) {
        window.location.href = result.url;
    } else {
        $(".authors_content_container").html(result);
    }
}
</script>

Controller

[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel, HttpPostedFileBase file)
{
    ...
    viewModel.OrginalImageUrl = file.FileName;
    ...
}

Above codes work fine

Question

As you see, I post file seperate from ViewModel. Is there a way to add HttpPostedFileBase file property to ViewModel and bind it to viewModel in view, And post it to controller in ViewModel?

I hope , I can explain.

EDIT:

This codes work fine. I dont want post , viewModel and HttpPostedFile seperately. I want something like this: (If it is possible.)

Model

public class AuthorViewModel
{
    public int Id { get; set; }

    [Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
    [Display(Name = "Yazar Adı")]

    HttpPostedFileBase file{ get; set; }
    ...
}

Controller

[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel)
{
    var file = viewModel.file;
    ...
}    

Thanks.

回答1:

Yes you can add AliRıza Adıyahşi.

Here is the property to do it:

public HttpPostedFileBase File { get; set; }

Now in you form you should add enctype as Xiaochuan Ma said:

@using (Html.BeginForm("_AddAuthor", "Authors", FormMethod.Post, new { id = "form_author", enctype="multipart/form-data" }))
{
    <div class="editor-label">
        <input type="file" name="file" id="file" />
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    ...

    <div class="submit-field">
        <input type="submit" value="Ekle" class="button_gray" />
    </div>
}

On you Controller action:

[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel, HttpPostedFileBase file)
{
    if(file!=null)
    {
        viewModel.File=file; //Binding your file to viewModel property
    }
    //Now you can check for model state is valid or not.
    if(ModelState.IsValid)
    {
        //do something
    }
    else
    {
        return View(viewModel);
    }
}

Hope it helps. Is this what you need ?


EDIT

There is nothing additional to do. Its automatically binding to viewModel.

[HttpPost]
public ActionResult _AddAuthor(AuthorViewModel viewModel)
{
      var uploadedfile = viewModel.File;// Here you can get the uploaded file.
      //Now you can check for model state is valid or not.
    if(ModelState.IsValid)
    {
        //do something
    }
    else
    {
        return View(viewModel);
    }
}

This worked for me !



回答2:

Yes, you can add HttpPostedFileBase in to your ViewModel, and add enctype = "multipart/form-data" to your From in HTML.

Check with this link: MVC. HttpPostedFileBase is always null