如何编写“Html.BeginForm"在剃刀 [英] How to write "Html.BeginForm" in Razor

查看:22
本文介绍了如何编写“Html.BeginForm"在剃刀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样写:

form action="Images" method="post" enctype="multipart/form-data"

form action="Images" method="post" enctype="multipart/form-data"

它有效.

但是在带有@"的 Razor 中它不起作用.我做错了吗?

But in Razor with '@' it doesn't work. Did I make any mistakes?

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                             new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)

    <fieldset>

        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />

    </fieldset>
}

我的控制器如下所示:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload() 
{
    foreach (string file in Request.Files)
    {
        var uploadedFile = Request.Files[file];
        uploadedFile.SaveAs(Server.MapPath("~/content/pics") + 
                                      Path.GetFileName(uploadedFile.FileName));
    }

    return RedirectToAction ("Upload");
}

推荐答案

以下代码工作正常:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

并按预期生成:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

另一方面,如果您在其他服务器端构造的上下文中编写此代码,例如 ifforeach,则应删除 @using 之前.例如:

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

就您的服务器端代码而言,这里是如何进行:

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

这篇关于如何编写“Html.BeginForm"在剃刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆