提交asp.net mvc 2表单时的空模型

时间:2010-09-24 14:41:19

标签: asp.net-mvc-2 file-upload

我在控制器和视图中有以下代码。问题是模型(Photo是实体框架实体)是空的(所有字段都是空的)。为什么呢?

// GET: /Admin/Photo/Create

    public ActionResult Create()
    {
        return View();
    } 

    //
    // POST: /Admin/Photo/Create

    [HttpPost]
    public ActionResult Create(int id, FormCollection collection)
    {
        try
        {
            var file = (HttpPostedFileBase) Request.Files[0];
            if (file != null && file.FileName != null)
            {
                var filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Photos/Product/", Path.GetFileName(file.FileName));
                file.SaveAs(filename);
                var photo = new Photo();
                photo.Description = collection["Description"];
                photo.Main = collection["Main"].Contains("true");
                photo.Filename = Path.GetFileName(file.FileName);
                photo.Product_Id = id;
                Entities.AddToPhotos(photo);
                Entities.SaveChanges();
            }
            else
            { 
                ModelState.AddModelError("", "Plik musi zostać załadowany.");
                return View();
            }


            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

<h2>Create</h2>

<% using (Html.BeginForm(null, null, null, FormMethod.Post, new {enctype = "multipart/form-data" })) {%>
    <%: Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Fields</legend>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Description) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Description) %>
            <%: Html.ValidationMessageFor(model => model.Description) %>
        </div>

        <div class="editor-label">
            <label for="MainContent_file">Plik: </label>
        </div>
        <div class="editor-field">
            <asp:FileUpload ID="file" runat="server" />
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Main) %>
        </div>
        <div class="editor-field">
            <%: Html.CheckBoxFor(model => model.Main) %>
            <%: Html.ValidationMessageFor(model => model.Main) %>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

<div>
    <%: Html.ActionLink("Back to List", "Index") %>
</div>

更新:我检查了这个集合,其中填入了适当的字段,但它们都是无效的。

2 个答案:

答案 0 :(得分:1)

检查以确保生成的html中的name属性与您的集合名称匹配。您也可以将public ActionResult Create(int id, FormCollection collection)更改为public ActionResult Create(int id, YourViewModel model),以便将帖子值自动映射到模型。

答案 1 :(得分:0)

检查浏览器中的html源代码。

它可能会将它们发送为:“Photo.Description”