4

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
  • Not similar, my codes are working. I asked different thing. Commented Feb 13, 2013 at 6:47

2 Answers 2

3

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 !

Sign up to request clarification or add additional context in comments.

6 Comments

misunderstood, review edited Question. I use a plugin, so there is no need enctype. code work...
I want to put HttpPostedFileBase in to ViewModel.
@AliRızaAdıyahşi you can put HttpPostedFileBase in vm, but how can you fill it in your view. we dont have helper for <input type=file right ?
Yes, I've already asked this how can I fill it in my view? Is it possible to bind file to VM with another way?
@AliRızaAdıyahşi Please check my edit. try placing the debugger in your action result and check whether you have got the posted file to viewModel or not
|
0

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

1 Comment

misunderstood, review edited Question. I use a plugin, so there is no need enctype. code work...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.