Por medio de un formulario Modal y usando una función ajax guardo una entidad Material y un archivo del tipo jpeg.
Este es mi vista modal:
@model MaterialViewModel
@{
ViewBag.Title = "Nuevo material";
Layout = null;
}
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Content/js/fileUpload.js"></script>
<link href="~/Content/css/fileUpload.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui.js"></script>
<link href="~/Content/popup/popupstyle.css" rel="stylesheet" />
<div class="modal-header modal-header-success">
<h3 class="modal-title" style="text-align: center;">
xxxxx
<button type="button" class="close panelTitleTxt glyphicon glyphicon-remove landing-icon" data-dismiss="modal" aria-hidden="true"></button>
</h3>
</div>
@using (Html.BeginForm("CreateForCategory", "CategoriasMateriales", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="modal-body">
@Styles.Render("~/Content/toastr")
<br />
<div class="form-horizontal">
@Html.HiddenFor(x => x.CategoriaId)
@Html.ValidationSummary(true, "", new {@class = "text-danger"})
<div class="form-group">
@Html.LabelFor(model => model.CategoriaId, htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})
<div class="col-sm-8">
@Html.DropDownListFor(x => x.CategoriaId, Model.CategoriasMaterialViewModel, new {@class = "form-control", @disabled = "disabled"})
@Html.ValidationMessageFor(model => model.CategoriaId, "", new {@class = "label label-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Descripcion, htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})
<div class="col-sm-8">
@Html.EditorFor(model => model.Descripcion, new {htmlAttributes = new {@class = "form-control", maxlength = "200"}})
@Html.ValidationMessageFor(model => model.Descripcion, "", new {@class = "label label-danger"})
</div>
</div>
<div class="form-group">
@Html.Label("Imagen", htmlAttributes: new {@class = "control-label col-sm-3 popup-labelfont"})
<div class="col-md-offset-0 col-sm-offset-0 col-sm-8">
<!-- image-preview-filename input [CUT FROM HERE]-->
<div class="input-group image-preview">
<input type="text" class="form-control image-preview-filename" disabled="disabled"> <!-- don't give a name === doesn't send on POST/GET -->
<span class="input-group-btn">
<!-- image-preview-clear button -->
<button type="button" class="btn btn-danger image-preview-clear" style="display: none;">
<span class="glyphicon glyphicon-remove"></span> Clear
</button>
<!-- image-preview-input -->
<div class="btn btn-info image-preview-input">
<span class="glyphicon glyphicon-folder-open"></span>
<span class="image-preview-input-title">Browse</span>
<input type="file" accept="image/png, image/jpeg, image/gif" name="upload" /> <!-- rename it -->
</div>
</span>
</div><!-- /input-group image-preview [TO HERE]-->
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input class="btn btn-success" id="btnSave" type="submit" value="Guardar"/>
<input aria-hidden="true" class="btn btn-md btn-warning" data-dismiss="modal" id="btncancel" type="button" value="Cancelar"/>
</div>
</div>
<div>
@Scripts.Render("~/bundles/toastr")
@Html.Partial("_Toastr")
</div>
</div>
</div>
}
<script>
$('form').submit(function () {
$('#myModal').on('hidden.bs.modal', function () {
window.LoadMateriales();
});
});
$('.modal').modal({
keyboard: true,
show: false
});
// Jquery draggable
$('.modal-dialog').draggable({
handle: ".modal-header"
});
</script>
Este es mi script ajax:
$('form').submit(function () {
var $form = $(this);
$.ajax({
url: this.action,
type: this.method,
contentType: this.enctype,
dataType: 'json',
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
//Refresh
//location.reload();
$('#replacetarget').load(result.url);
} else {
$('#myModalContent').html(result);
//bindForm();
}
}
});
});
La cual se comunica con este metodo de mi controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateForCategory(MaterialViewModel material, HttpPostedFileBase upload)
{
var materialDomain = Mapper.Map<MaterialViewModel, Material>(material);
if (upload != null && upload.ContentLength > 0)
{
var imagen = new Imagen
{
Nombre = System.IO.Path.GetFileName(upload.FileName),
TipoContenido = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
imagen.Contenido = reader.ReadBytes(upload.ContentLength);
}
materialDomain.Imagen = imagen;
}
_materialRepository.Create(materialDomain);
string url = Url.Action("MaterialesPorCategoriaIndex", "CategoriaMateriales");
return Json(new { success = true, url = url }, JsonRequestBehavior.AllowGet);
}
El tema es que si no trato de cargar la imagen junto con la entidad el json retornado por el método llega a la función y puedo cerrar el modal o mostrar algún mensaje, pero si trato de cargar la imagen junto con la entidad el json ya no regresa a la función y este me genera un nuevo html solo con la cadena cargada al objeto json.
¿Alguna idea de como solucionar este problema?