I have a page wich it has a form and everythings works correctly.
my question is for when my model state is not valid, then how to return contact us to index view not create view
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Email,Phone,Message,Date")] Contact_US contact_US)
{
if (ModelState.IsValid)
{
db.Contact_US.Add(contact_US);
db.SaveChanges();
MailMessage mail = new MailMessage();
mail.To.Add("");
mail.From = new MailAddress("");
mail.Subject = contact_US.Email;
string body = contact_US.Message;
mail.Body = "Phone:" + contact_US.Phone + "<br />Name:" + contact_US.Name +"<br />Email:"+contact_US.Email+ "<br /><br />" + body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("", "");// Enter seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
TempData["ResultMessage"] = "Thank you for your enquiry and or enrolment. we will attend to this submission and come back to you soon";
TempData["TimeMessage"] = "Your entry was received on"+DateTime.Now;
return RedirectToAction("Index");
}
return View(contact_US);
}
in this situation if model state is not valid it looks fore create view but i don't want to have a create view . I just want to bring contact us to index page.
this is my index view
#using (Html.BeginForm("Create", "Contact_Us", FormMethod.Post, new { #id = "contactusform" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group hidden">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Message, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12 contactusmsg">
#Html.TextAreaFor(model => model.Message, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Message, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group contactuspostbtn">
<div class="col-md-12">
<input id="postcontactusmessage" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
}
Appreciate Any help
If you just want to call a view and pass in correct model then you can use overload with view name as in below cases:
Load view with Model:
return View("Index", contact_US); //Index is View name and contact_US is the Model.
Load view without Model:
return View("Index");
Make sure the Model expected by the view and what you are passing from the action are matching.
Ideally, except some specific cases better to stay close to MVC practices. Ex: If user provided data from Contact page then it would be nice and easily understood to redirect them back to Contact page instead of some other page. This need lot of caution especially while renaming the views etc.
Hope this help you.
Related
I'm working on an asp.net Mvc Project.
I want to implement a File up_loader to upload images. my File up_loader should create the correct address and fill the imgURL field of database.
my view looks like this
here is my view
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Hotel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StateId, "StateId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StateId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HotelRate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HotelRate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HotelRate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HotelName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HotelName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HotelName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.ImageURL, new { htmlAttributes = new { #class = "form-control" } })*#
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
#Html.ValidationMessageFor(model => model.ImageURL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
and here is my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,StateId,HotelRate,HotelName,Description,ImageURL")] Hotel hotel,HttpPostedFileBase file)
{
if (file != null)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/img/hotel"), fileName);
file.SaveAs(path);
hotel.ImageURL = path;
}
if (ModelState.IsValid)
{
db.Hotels.Add(hotel);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.StateId = new SelectList(db.States, "Id", "StateName", hotel.StateId);
return View(hotel);
}
after saving data everything will be save correctly except ImgURL. its data is null after saving and also even before code comes t this command if (ModelState.IsValid){...}.
I suppose whole part
if (file != null)
{
//...
}
Not working
You should use
Html.BeginForm("", "", FormMethod.Post, new { enctype="multipart/form-data"})
You don't have file becouse on POST selected file data is not been serialized without enctype="multipart/form-data" attribute on form tag.
I am new to asp.net mvc.
I have a employee registration view, where i have a dropdown-list for for department, I want to bind the dropdown-list with a database table tblDepartment and i have did it. But I don't know how to get the select item of the list on post-back.
Employee Controller
[HttpGet]
public ActionResult AddEmployee()
{
ViewBag.Departments = new SelectList(_department.GetAll(), "id", "name");
return View(_employee.Get());
}
[HttpPost]
public ActionResult AddEmployee(FormCollection data)
{
var emp = _employee.Get();
emp.name = data["name"];
emp.age = Convert.ToInt32(data["age"]);
emp.dept_id = Convert.ToInt32(data["dept_id"]); // return dept_id 0 always.
emp.city = data["city"];
_employee.Insert(emp);
return RedirectToAction("Index");
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.name, "Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.age, "Age", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dept_id, "Department", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Departments", "Select Department")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.city, "City", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.city, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.city, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
You are defining your dropdownlist with name DropDownLists i.e. #Html.DropDownList("Departments" which will be the name of the drop-down list so it will be rendered like:
<select name="Departments">
</select>
and in form post the values are posted in key value pair and the key is the name of the input element.
But in post request you are finding the posted value in dept_id, you need to read from correct key in FormCollection which would be:
emp.dept_id = Convert.ToInt32(data["Departments"]);
Side Note:
You should be using strongly typed helpers to post values directly to model and let the model binder do the magic for you, instead of populating the model manually.
For that your helper method would be DropDownListFor :
#Html.DropDownListFor(x=>x.dept_id ,ViewBag.Departments as SelectList, "Select Department")
and in action method set the parameter to be mode object:
[HttpPost]
public ActionResult AddEmployee(Employee employee)
{
If(ModelState.IsValid)
{
_employee.Insert(employee);
return RedirectToAction("Index");
}
else
{
return View(employee);
}
}
Hi I am trying to default a date with 'DateTime.Now' in a create view. And setting an 'Active' field to 'true'
The following code does that in the the following action in the controller:
// POST: RequestTypes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,RequestTypeDescription,LastUpdated,Active,Team")] RequestType requestType)
{
if (ModelState.IsValid)
{
db.RequestTypes.Add(requestType);
requestType.LastUpdated = System.DateTime.Now;
requestType.Active = true;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription", requestType.Team);
return View(requestType);
}
That is the httppost code which defaults when the save is made.
What I want to do is to default those fields so that they show when the create view first gets launched - with the following code in the following action:
// GET: RequestTypes/Create
public ActionResult Create()
{
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription");
ViewBag.LastUpdated = System.DateTime.Now;
return View();
}
My Create View code is the standard created by MVC scaffolding:
#model ManageHR5.Models.RequestType
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>RequestType</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.RequestTypeDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequestTypeDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RequestTypeDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastUpdated, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastUpdated, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastUpdated, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Team, "Team", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Team", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Team, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")}
When I run the app, and launch the create page, the defaults don't show up when the create page is launched.
What am I not understanding?
(A newbie to MVC :( )
You set them in the model on the Get for display purposes
// GET: RequestTypes/Create
public ActionResult Create() {
ViewBag.Team = new SelectList(db.Teams, "Id", "TeamDescription");
var model = new RequestType();
model.LastUpdated = System.DateTime.Now;
model.Active = true;
return View(model);
}
But like indicated in the provided comment
You set them immediately before you save the object in the POST method
I'm working with a standard razor view with form data. I want to pass the input form data to my controller after pressing the submit button. My view looks like this:
#model CareSource.ReleaseAssistant.Models.Prime.Team
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create New Team</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Team</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Abbreviation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Abbreviation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Abbreviation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreatedOn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreatedOn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreatedOn, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ModifiedOn, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModifiedOn, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModifiedOn, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
The problem is that the information in the form is not being passed back to my controller to be handled by my action method. I'm trying create a new entry in my database using web api. My action method looks like this:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
if (ModelState.IsValid)
{
HttpEndPointContext httpEndPoint = new HttpEndPointContext()
{
AuthenticationMethod = HttpAuthenticationMethods.None,
Ssl = false,
HttpMethod = HttpMethod.Post,
//Path = "localhost:32173/api/team/",
QueryStrings = null,
};
IProcessResult result = HttpConnectionManager.Current.SendMessage(httpEndPoint);
var response = result.ResponseData.ToString();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Most of the code in this project was generated using Codesmith Generator and uses the MicroORM called PetaPoco.
Since your form is strongly typed to an instance of Team and you are using that to generate the input form fields, you can use Team object as the parameter of your HttpPost method.
HttpPost]
public ActionResult Create(Team model)
{
if (ModelState.IsValid)
{
//access model.Properties
}
return View(model);
}
Do use Team model as parameter remove formCollection and try
Please update your View with the given code :
#using (Html.BeginForm("Create", "YourControllerName", FormMethod.Post, new { id = "form" }))
{
//Copy your current code as it is here.
}
During Create, i always get the ModelState.IsValid as false and dont save my image in the database
In my model, the field for saving images is
[Required]
public byte[] BookingImage { get; set; }
In my controller, I have the following code:
public ActionResult Create([Bind(Include = "BookingId,BookingName,BookingDescription,ProviderId,EmployeeId,StatusId,BookingDuration,BookingTime, BookingImage, BookingRequestAmount,BookingReserveDeadline")] Booking booking, HttpPostedFileBase BookingImageHidden)
{
using (var ms = new MemoryStream())
{
BookingImageHidden.InputStream.CopyTo(ms);
booking.BookingImage = ms.ToArray();
}
if (ModelState.IsValid)
{
db.Booking.Add(booking);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.EmployeeId = new SelectList(db.Employee, "EmployeeId", "EmployeeName", booking.EmployeeId);
ViewBag.ProviderId = new SelectList(db.Providers, "ProviderId", "ProviderName", booking.ProviderId);
ViewBag.StatusId = new SelectList(db.Status, "StatusId", "StatusName", booking.StatusId);
return View(booking);
}
In my View, this is the code around the Image:
#model Sword.Models.Booking
#using (Html.BeginForm("Create", "bookings", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Booking</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.BookingName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProviderId, "ProviderId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProviderId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ProviderId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmployeeId, "EmployeeId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("EmployeeId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.EmployeeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, "StatusId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StatusId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingDuration, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingDuration, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingDuration, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingImage, new { htmlAttributes = new { #class = "form-control" } })
<input name="BookingImageHidden" type="file" />
#Html.ValidationMessageFor(model => model.BookingImage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingRequestAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingRequestAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingRequestAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingReserveDeadline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingReserveDeadline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingReserveDeadline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
In my model, the field for saving images is [Required] public byte[]
BookingImage { get; set; }
Why do you even have a property in your model for the image if you are going to manually be reading it.
So simply consider using view models with the proper types (please notice that I am bolding the word view model here):
public class BookingViewModel
{
[Required]
public HttpPostedFileBase BookingImage { get; set; }
... some other properties that you need populated from the client
}
and then in your controller action get rid of these hacks and use the view model:
public ActionResult Create(BookingViewModel bookingVm)
{
if (ModelState.IsValid)
{
// In the MapFromViewModel you will obviously only
// map the properties that you need to be populated
// in your domain model from the view model. That's where
// you should put the logic of reading the image stream into a
// byte array which is what your domain model expects.
Booking booking = MapFromViewModel(bookingVm);
db.Booking.Add(booking);
db.SaveChanges();
return RedirectToAction("Index");
}
...
}
You got into all those troubles because you didn't use view models in the first place but rather you had your controller actions take your domain models as parameter which is one of the worst MVC design patterns I have ever seen in my life.