我的剃刀html:
@using (Html.BeginForm("CreateTestinomialPage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Fill Form</legend>
@Html.HiddenFor(m => m.PostedTypeId)
<div class="editor-label">
@Html.DisplayName("Image Upload")
</div>
<div class="editor-field" >
@*<input type="file" name="file" id="file" />*@
@Html.TextBoxFor(m => m.file,new{type="file"})
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Message)
@Html.ValidationMessageFor(model => model.Message)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Postedby)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Postedby)
@Html.ValidationMessageFor(model => model.Postedby)
</div>
<p>
<input type="submit" value="Create" />
</p>
<div id="result"></div>
</fieldset>
}
我的脚本:
<script type="text/javascript">
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
},
complete: function () {
$('form').each(function () {
this.reset(); //Here form fields will be cleared.
});
},
});
}
return false;
});
});
</script>
我的控制员:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateTestinomialPage(TestinomialsModels models,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int maxcontentlength = 1024 * 1024 * 3;
string[] AllowedExtension = new string[] { ".jpg", ".gif", ".png" };
if (!AllowedExtension.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedExtension));
}
else if (file.ContentLength > maxcontentlength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + maxcontentlength + " MB");
}
else
{
var filename = Path.GetFileName(models.file.FileName);
models.ImagePath = ConfigurationManager.AppSettings["ImagesavePath"].ToString() + filename;
postservices.AddTestinomailPost(models);
var path = Path.Combine(Server.MapPath("~/Content/Upload/Images"), filename);
models.file.SaveAs(path);
return Content("Successfully Submiited");
}
}
}
return Content("An error occur while saved Plese try again..");
}
有controllerAction null httppostedbasefile ..