表单文件上载与其他TextBox输入+创建自定义表单操作属性

时间:2010-03-31 19:02:06

标签: asp.net-mvc file-upload

我正在尝试创建一个表单,用户可以在其中输入典型的表单值文本框等,还可以上传文件作为表单提交的一部分。这是我的View代码,可以看到文件上传由MCF ID标识:

<% using (Html.BeginForm("Create", "Problem", FormMethod.Post, new { id = "ProblemForm", enctype = "multipart/form-data" }))
   {%>

        <p>
            <label for="StudentEmail">Student Email (*)</label>
            <br />
            <%= Html.TextBox("StudentEmail", Model.Problem.StudentEmail, new { size = "30", maxlength=26 })%>
            <%= Html.ValidationMessage("StudentEmail", "*") %>
        </p>
        <p>
            <label for="Type">Communication Type (*)</label>
            <br />
            <%= Html.DropDownList("Type") %>
            <%= Html.ValidationMessage("Type", "*") %>
        </p>
        <p>
            <label for="ProblemDateTime">Problem Date (*)</label>
            <br />
            <%= Html.TextBox("ProblemDateTime", String.Format("{0:d}", Model.Problem.ProblemDateTime), new { maxlength = 10 })%>
            <%= Html.ValidationMessage("ProblemDateTime", "*") %>
        </p>
        <p>
            <label for="ProblemCategory">Problem Category (* OR Problem Outline)</label>
            <br />
            <%= Html.DropDownList("ProblemCategory", null, "Please Select...")%>
            <%= Html.ValidationMessage("ProblemCategory", "*")%>
        </p>
        <p>
            <label for="ProblemOutline">Problem Outline (* OR Problem Category)</label>
            <br />
            <%= Html.TextArea("ProblemOutline", Model.Problem.ProblemOutline, 6, 75, new { maxlength = 255 })%>
            <%= Html.ValidationMessage("ProblemOutline", "*") %>
        </p>
        <p>
            <label for="MCF">Mitigating Circumstance Form</label>
            <br />
            <input id="MCF" type="file" />
            <%= Html.ValidationMessage("MCF", "*") %>
        </p>
        <p>
            <label for="MCL">Mitigating Circumstance Level</label>
            <br />
            <%= Html.DropDownList("MCL") %>
            <%= Html.ValidationMessage("MCL", "*") %>
        </p>
        <p>
            <label for="AbsentFrom">Date Absent From</label>
            <br />
            <%= Html.TextBox("AbsentFrom", String.Format("{0:d}", Model.Problem.AbsentFrom), new { maxlength = 10 })%>
            <%= Html.ValidationMessage("AbsentFrom", "*") %>
        </p>
        <p>
            <label for="AbsentUntil">Date Absent Until</label>
            <br />
            <%= Html.TextBox("AbsentUntil", String.Format("{0:d}", Model.Problem.AbsentUntil), new { maxlength = 10 })%>
            <%= Html.ValidationMessage("AbsentUntil", "*") %>
        </p>
        <p>
            <label for="AssessmentID">Assessment Extension</label>
            <br />
            <%= Html.DropDownList("AssessmentID") %>
            <%= Html.ValidationMessage("AssessmentID", "*") %>

            <%= Html.TextBox("DateUntil", String.Format("{0:d}", Model.AssessmentExtension.DateUntil), new { maxlength = 16 })%>
            <%= Html.ValidationMessage("DateUntil", "*") %>
        </p>
        <p>
            <label for="Details">Assessment Extension Details</label>
            <br />
            <%= Html.TextArea("Details", Model.AssessmentExtension.Details, 6, 75, new { maxlength = 255 })%>
            <%= Html.ValidationMessage("Details", "*") %>
        </p>
        <p>
            <label for="RequestedFollowUp">Requested Follow Up</label>
            <br />
            <%= Html.TextBox("RequestedFollowUp", String.Format("{0:d}", Model.Problem.RequestedFollowUp), new { maxlength = 16 })%>
            <%= Html.ValidationMessage("RequestedFollowUp", "*") %>
        </p>
        <p>
            <label for="StaffEmail">Staff</label>
            <br />
            <%= Html.ListBox("StaffEmail", Model.StaffEmail, new { @class = "multiselect" })%>
            <%= Html.ValidationMessage("StaffEmail", "*")%>
        </p>
        <p>
            <input class="button" type="submit" value="Create Problem" />
        </p>

这是我的控制器代码:

        [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Problem problem, AssessmentExtension assessmentExtension, Staff staffMember, HttpPostedFileBase file, string[] StaffEmail)
    {
        if (ModelState.IsValid)
        {
            try
            {

                Student student = studentRepository.GetStudent(problem.StudentEmail);
                Staff currentUserStaffMember = staffRepository.GetStaffWindowsLogon(User.Identity.Name);

                var fileName = Path.Combine(Request.MapPath("~/App_Data"), Path.GetFileName(file.FileName));
                file.SaveAs(@"C:\Temp\" + fileName);

                if (problem.RequestedFollowUp.HasValue)
                {
                    String meetingName = student.FirstName + " " + student.LastName + " " + "Mitigating Circumstance Meeting";
                    OutlookAppointment outlookAppointment = new OutlookAppointment(currentUserStaffMember.Email, meetingName, (DateTime)problem.RequestedFollowUp, (DateTime)problem.RequestedFollowUp.Value.AddMinutes(30));
                }

                problemRepository.Add(problem);
                problemRepository.Save();

                if (assessmentExtension.DateUntil != null)
                {
                    assessmentExtension.ProblemID = problem.ProblemID;
                    assessmentExtensionRepository.Add(assessmentExtension);
                    assessmentExtensionRepository.Save();
                }

                ProblemPrivacy problemPrivacy = new ProblemPrivacy();
                problemPrivacy.ProblemID = problem.ProblemID;
                problemPrivacy.StaffEmail = currentUserStaffMember.Email;
                problemPrivacyRepository.Add(problemPrivacy);

                if (StaffEmail != null)
                {
                    for (int i = 0; i < StaffEmail.Length; i++)
                    {
                        ProblemPrivacy probPrivacy = new ProblemPrivacy();
                        probPrivacy.ProblemID = problem.ProblemID;
                        probPrivacy.StaffEmail = StaffEmail[i];
                        problemPrivacyRepository.Add(probPrivacy);
                    }
                }

                problemPrivacyRepository.Save();

                return RedirectToAction("Details", "Student", new { id = student.Email });

            }
            catch
            {
                ModelState.AddRuleViolations(problem.GetRuleViolations());
            }
        }

        return View(new ProblemFormViewModel(problem, assessmentExtension, staffMember));
    }

在我不得不切换到使用非AJAX文件上传之前,此表单工作正常,这是由于在启用我需要使用的Windows身份验证时Flash出现问题。

看来,当我提交表单时,文件没有发送,我不确定为什么?我也没有成功找到一个在线示例,其中文件上传与其他输入类型一起使用。

我的另一个问题是,对于Create和Edit操作,我已经为我的表单使用了PartialView,以使我的应用程序具有更高的代码重用率。表单操作通常只使用:

生成
Html.BeginForm()

这会根据正在使用的Url编辑或创建来填充操作。但是,在填充HTML属性时,您必须提供操作和控制器值以传递HTML属性。

using (Html.BeginForm("Create", "Problem", FormMethod.Post, new { id = "ProblemForm", enctype = "multipart/form-data" }))

是否有可能以某种方式根据URL填充操作和控制器值以维护代码重用?在键入此内容时考虑它我可以在原始控制器操作请求视图数据中设置两个值,然后使用viewdata值填充值?

对这两个问题的任何帮助将不胜感激,我是asp.net mvc的新手: - )

谢谢,

乔恩

ANSWER

好的家伙解决了这个问题,而且非常简单,我的表单文件组件上没有HTML名称属性:

<input id="MCF" name="MCF" type="file" />

现在这与我的方法签名绑定了!

2 个答案:

答案 0 :(得分:0)

对于第一个问题,看起来您的操作方法签名是错误的。由于您的fileInput的ID为MCF,因此HttpPostedFileBase参数应具有相同的名称,以便模型绑定器知道绑定到该操作方法参数。

E.g。

public ActionResult Create(Problem problem, AssessmentExtension assessmentExtension, Staff staffMember, HttpPostedFileBase mcf, string[] StaffEmail)

至于第二个问题......你可以尝试这样的事情:

<form method="post" id="ProblemForm" action="<%= Url.Action(ViewContext.RouteData.Values["action"].ToString()) %>" enctype="multipart/form-data">

当前的控制器也在RouteData.Values,但如果您在该区域之后,那将会在RouteData.DataTokens

HTHS,
查尔斯

答案 1 :(得分:0)

好的家伙解决了这个问题,而且非常简单,我的表单文件组件上没有HTML名称属性:

<input id="MCFile" name="MCFile" type="file" />

我更改了方法签名以匹配名称:

public ActionResult Create(Problem problem, AssessmentExtension assessmentExtension, Staff staffMember, HttpPostedFileBase MCFFile, string[] StaffEmail)

现在这与我的方法签名绑定了!