开发者

How do I include a Telerik file upload in my MVC3 model binding?

开发者 https://www.devze.com 2023-03-18 06:32 出处:网络
I don\'t li开发者_运维技巧ke to have to use parameters to my POST action methods in addition to my view model parameter.However, for a file upload using the Telerik Upload helper, it seems I am forced

I don't li开发者_运维技巧ke to have to use parameters to my POST action methods in addition to my view model parameter. However, for a file upload using the Telerik Upload helper, it seems I am forced to do this. The posted value is IEnumerable<HttpPostedFileBase>. Is there any way I can also bind this to the model without the effort of custom model binding.


I don't like to have to use parameters to my POST action methods in addition to my view model parameter.

Me neither. That's why I use view models:

public class MyViewModel
{
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
    public string Foo { get; set; }
    public string Bar { get; set; }
    ...
}

and then:

[HttpPost]
public ActionResult Upload(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    if (model.Files != null)
    {
        foreach (var file in model.Files)
        {
            if (file != null && file.ContentLength > 0)
            {
                // process the uploaded file
            }
        }
    }
    ...
}


Remember that the name of the control (Upload().Name(***)) should be the same as model's property.

public class MyViewModel
{
    public IEnumerable<HttpPostedFileBase> ManyFiles { get; set; }
    ...
}
// ...
@Html.Kendo().Upload().Name("ManyFiles")

or

public class MyViewModel
{
    public HttpPostedFileBase OneFile { get; set; }
    ...
}
// ...
@Html.Kendo().Upload().Name("OneFile").Multiple(false)
0

精彩评论

暂无评论...
验证码 换一张
取 消