I am having trouble putting image upload field within the rest of the fieldset, mainly becaouse i need two Actions for one Form, correct me if I am wrong! Aloso when using Model to render fields in View, there is no @Html.UploadField or similar.... Any ideas?
My goal is to save image in the same row as the rest of the form...
MODEL:
public class MyModel
{
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set; }
[Display(Name = "Author: ")]
public string Author { get; set; }
[Display(Name = "Title: ")]
public string Title { get; set; }
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
}
VIEW:
@model namespace.MyModel
@using (Html.BeginForm("AddForm", "Admin"))
{
<div>
<fieldset>
<legend>New Article</legend>
<div class="editor-label">
@Html.LabelFor(m => m.Author)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Author)
@Html.ValidationMessageFor(m => m.Author)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Title)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Title)
</div>
@using (Html.BeginForm("SaveImage", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">Image</div>
<div class="editor-field">
<div>Upload image: <input type="file" name="Image" /></div>
</div>
}
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
</div>
}
CONTROLLER
//AddForm
[HttpPost]
public ActionResult AddForm(MyModel model)
{
if (ModelState.IsValid)
{
string connStr = ConfigurationManager.ConnectionStrings["AdminServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into MyTable(DbAuthor, DbTitle) values(@author, @title)", connection))
{
command.Parameters.AddWithValue("@author", model.Author);
command.Parameters.AddWithValue("@title", model.Title);
command.ExecuteNonQuery();
}
}
}
return RedirectToAction("Index", "Admin");
}
//SaveImage
[Authorize]
[HttpPost]
public ActionResult SaveImage(MyModel zan, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null)
{
zan.ImageMimeType = image.ContentType;
zan.ImageData = new byte[image.ContentLength];
image.InputStream.Read(zan.ImageData, 0, image.ContentLength);
string connStr = ConfigurationManager.ConnectionStrings["AdminServices"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand("insert into MyTable(DbImage) values(@image)", connection))
{
command.Parameters.AddWithValue("@image", zan.ImageData);
command.ExecuteNonQuery();
}
}
return RedirectToAction("Index", "Admin");
}
}
return RedirectToAction("Index", "Admin");
}
My problem is to put these two methods into one, and to have native MVC3 uploadfield in View...