سؤال

حسنًا ، لقد كنت أذهب إلى هذا لعدة ساعات ، وأنا ببساطة لا أستطيع العثور على الحل.

أريد الحصول على بعض البيانات من المستخدم الخاص بي. أولاً ، أستخدم وحدة تحكم لإنشاء عرض يتلقى نموذجًا:

public ViewResult CreateArticle()
{
    Article newArticle = new Article();
    ImagesUploadModel dataFromUser = new ImagesUploadModel(newArticle);
    return View(dataFromUser);
}

ثم لدي وجهة نظر:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">

    <h2>AddArticle</h2>

    <% using (Html.BeginForm("CreateArticle", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" })){ %>


                <%= Html.LabelFor(model => model.newArticle.Title)%>
                <%= Html.TextBoxFor(model => model.newArticle.Title)%>

                <%= Html.LabelFor(model => model.newArticle.ContentText)%>
                <%= Html.TextBoxFor(model => model.newArticle.ContentText)%>

                <%= Html.LabelFor(model => model.newArticle.CategoryID)%>
                <%= Html.TextBoxFor(model => model.newArticle.CategoryID)%>

                <p>
                    Image1: <input type="file" name="file1" id="file1" />
                </p>
                <p>
                    Image2: <input type="file" name="file2" id="file2" />
                </p>

            <div>
                <button type="submit" />Create
            </div>



    <%} %>


</asp:Content>

وأخيراً - وحدة التحكم الأصلية ، ولكن هذه المرة تم تكوينها لقبول البيانات:

   [HttpPost]
    public ActionResult CreateArticle(ImagesUploadModel dataFromUser)
    {
        if (ModelState.IsValid)
        {
            HttpPostedFileBase[] imagesArr;
            imagesArr = new HttpPostedFileBase[2]; 
            int i = 0;
            foreach (string f in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[f];
                if (file.ContentLength > 0)
                    imagesArr[i] = file;
            }

لا يهم بقية وحدة التحكم هذه لأنه بغض النظر عن ما أفعله ، count سمة Request.Files (أو Request.Files.Keys) لا يزال 0. لا يمكنني العثور على طريقة لتمرير الملفات من النموذج (يمر النموذج على ما يرام).

هل كانت مفيدة؟

المحلول

قد ترغب في التفكير في عدم نشر الملفات مع بقية النموذج- هناك أسباب وجيهة وطرق أخرى يمكنك تحقيق ما تريد.

أيضا ، تحقق من هذا السؤال و هذه النصيحة بخصوص تحميل الملفات في MVC.

نصائح أخرى

يمكنك إضافة الملفات إلى نموذج العرض الخاص بك:

public class ImagesUploadModel
{
    ...
    public HttpPostedFileBase File1 { get; set; }
    public HttpPostedFileBase File2 { get; set; }
}

وثم:

[HttpPost]
public ActionResult CreateArticle(ImagesUploadModel dataFromUser)
{
    if (ModelState.IsValid)
    {
        // Use dataFromUser.File1 and dataFromUser.File2 directly here
    }
    return RedirectToAction("index");
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top