Я создал регистрационную форму, в которой каждый пользователь может отправить свою информацию вместе с загружаемым файлом на сервер.Хотя я не определил поле Обязательное, форма не будет отправлена, пока файл не будет загружен для выбора.Я думаю, что есть проблема с кодом контроллера,
Код, который я написал в контроллере:
public ActionResult Create([Bind(Include =" ID,FullName,Mellicode,PostTime,Mobile,Telephone,Email,Age,Gender,Address,Postalcode,LastEducationalCertificate,FieldOfStudy,JobExperience,MaritalStatus,Comment,FilePathName,Invitation,Invalidity,Recruitment")] RegisterForm registerForm, HttpPostedFileBase UploadFile)
{
var myUniqueFileName = string.Format(@"{0}.txt",Guid.NewGuid());
if (ModelState.IsValid)
{
string strFileExtension = System.IO.Path.GetExtension(UploadFile.FileName).ToUpper();
string strContentType = UploadFile.ContentType.ToUpper();
if (UploadFile.ContentLength > 100 * 1024)
{
return View("Error");
}
else if(UploadFile.ContentLength<100*1024 && UploadFile !=null)
{
registerForm.FilePathName = myUniqueFileName + UploadFile.FileName;
if (System.IO.Directory.Exists(strPath) == false)
{
System.IO.Directory.CreateDirectory(strPath);
}
string strPathName =
string.Format("{0}\\{1}", strPath, registerForm.FilePathName);
UploadFile.SaveAs(strPathName);
}
db.Registers.Add(registerForm);
db.SaveChanges();
return RedirectToAction("Back");
}
return View(registerForm);
}
Для загрузки также используется следующий метод расширения:
public static class UploadHelper
{
public static MvcHtmlString Upload(this HtmlHelper helper, string name, object htmlAttributes = null)
{
//helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))
TagBuilder input = new TagBuilder("input");
input.Attributes.Add("type", "file");
input.Attributes.Add("id", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(name));
input.Attributes.Add("name", helper.ViewData.TemplateInfo.GetFullHtmlFieldName(name));
input.Attributes.Add("class", "required");
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
input.MergeAttributes(attributes);
}
return new MvcHtmlString(input.ToString());
}
}
загрузка кода:
<div class="form-group">
@Html.LabelFor(model => model.FilePathName, htmlAttributes: new { @class = "control-label col-md-10" })
<div class="col-md-10">
@Html.Upload("UploadFile", new { htmlAttributes = new { @class = "form-control demoInputBox ", type = "file", runat = "server" } })
@Html.ValidationMessageFor(model => model.FilePathName, "", new { @class = "text-danger" })
</div>
</div>
</div>
Я хочу использовать этот метод, если кто-то может поблагодарить меня