如何在asp.net mvc编辑器视图中访问我的文章数据



我已经得到了这个半自动生成的代码,但我不确定Post数据保存在哪里,也不确定我如何访问控制器中的变量,以便验证并上传到我的数据库。

    @model FirstWeb.Models.Picture
@{
    ViewBag.Title = "Upload et billede";
}
<h2>Upload et billede</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <input type="file" name="file" id="file" />
        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.ConcertYear)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ConcertYear)
            @Html.ValidationMessageFor(model => model.ConcertYear)
        </div>
        <p>
            <input type="submit" value="Upload" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Tilbage til billeder", "Index")
</div>

您似乎正在尝试在此处上传文件。签出以下博客文章。您需要为表单使用multipart/form-data enctype才能上传文件。因此,第一步是修复表单定义:

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

然后更新视图模型,使其将上传的文件作为属性:

public class Picture
{
    public HttpPostedFileBase File { get; set; }
    public string Title { get; set; }
    public int ConcertYear { get; set; }
    ... some other properties used in the view
}

最后让您的控制器POST操作将此视图模型作为参数:

[HttpPost]
public ActionResult Foo(Picture model)
{
    if (!ModelState.IsValid)
    {
        // there were validation errors => re-display the view
        return View(model);
    }
    // the model is valid at this stage => check if the user uploaded a file
    if (model.File != null && model.File.ContentLength > 0)
    {
        // the user uploaded a file => process it ...
    }
    ...
} 

Edit操作应该将您的模型作为参数。

其项目将具有编辑后的值。

最新更新