Couldn't Upload File ASP.NET MVC - c#

I'm trying to create a create model object page. I'm using asp.net mvc with c#. In my project i'm trying to create a library application which has books and we can add book from application which has picture. So my Create Controller like this,
[HttpPost]
public ActionResult Create([Bind(Exclude = "id,bringBack,borrower,isBorrowed")]Book bookToCreate, HttpPostedFileBase picture1)
{
try
{
if (picture1.ContentLength > 0)
{
var fileName = Path.GetFileName(picture1.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/pictures"), fileName);
picture1.SaveAs(path);
}
// TODO: Add insert logic here
_entities.AddToLibrary(bookToCreate);
_entities.SaveChanges();
return RedirectToAction("ListBooks");
}
catch
{
return View();
}
}
and my view is like this,
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.Book>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Create</title>
</head>
<body>
<% using (Html.BeginForm(new { enctype = "multipart/form-data" }))
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.name) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.name) %>
<%: Html.ValidationMessageFor(model => model.name) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.author) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.author) %>
<%: Html.ValidationMessageFor(model => model.author) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.picture) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.picture) %>
<%: Html.ValidationMessageFor(model => model.picture) %>
</div>
<input type='file' name='picture1' id='picture1' />
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
I have tried many things but i couldn't upload any file. What can i do?

Try getting the posted file(s) from the Request instead.
var picture1 = this.Request.Files["picture1"];

In your Book model should be a preperty
HttpPostedFileBase picture1

Related

Asp.net MVC 2 Request.files[""] return null always

<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Movies.Models.StudentModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server">
<script type="text/javascript">
$(document).ready(function () {
//$('.date').datepicker({ dateFormat: "dd/mm/yy", Date: Date });
$('.date').datepicker();
$('.date').datepicker("setDate", new Date());
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#UImage').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function () {
readURL(this);
});
</script>
<h2>Create</h2>
<% using (Html.BeginForm("Create", "Student", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.StudentName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.StudentName) %>
<%: Html.ValidationMessageFor(model => model.StudentName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.RollNo) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.RollNo) %>
<%: Html.ValidationMessageFor(model => model.RollNo) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.STD) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.STD, Model.STDs, "Please Select Std", new { #class = "form-control" }) %>
<%: Html.ValidationMessageFor(model => model.STD)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Address) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Address)%>
<%: Html.ValidationMessageFor(model => model.Address)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Address2) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Address2)%>
<%: Html.ValidationMessageFor(model => model.Address2)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Image) %>
</div>
<div class="editor-field">
<input type='file' id="File1" name="File1" onchange="readURL(this)" />
<img id="UImage" src="#" height="300px" width="300px" alt="your image" />
<%: Html.ValidationMessageFor(model => model.Image)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.City) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.City)%>
<%: Html.ValidationMessageFor(model => model.City)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.ZIP) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ZIP)%>
<%: Html.ValidationMessageFor(model => model.ZIP)%>
<br />
<br />
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.DOB) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.DOB, new { #class = "date" })%>
<%: Html.ValidationMessageFor(model => model.DOB)%>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</form>
</asp:Content>
this is my aspx page where i used the jquery to show the uploaded image to the user.
The controller code is like
[HttpPost]
public ActionResult Create(StudentModel StudentEn,HttpPostedFileBase File1)
{
Student st = new Student();
HttpPostedFileBase file;
file = Request.Files["File1"];///it only access the name of the object of html."file1" is the name of the object
if (file != null && file.ContentLength > 0)
{
byte[] Image=null;
Image = new byte[file.ContentLength];
file.InputStream.Read(Image, 0, file.ContentLength);
StudentEn.Image=Image;
}
if (ModelState.IsValid)
{
st.Insert(StudentEn);
return RedirectToAction("Index");
}
else
{
StudentEn.STDs = getSelectedSTD(GetSTDList());
return View(StudentEn);
}
}
here is the controller code. where i always get the request.files null.
What do i have to change to upload image and store it into the database.
The problem is that you've two forms in your page which is confusing.
Try removing/Commenting the first form
i.e. <form id="form1" runat="server">
Modify the razor code as below
Try the razor code as below
<% = Html.BeginForm("Create", "Student", FormMethod.Post, new { enctype = "multipart/form-data" })%>
...............
..............
<% Html.EndForm(); %>
remove using and try
Try below code..use File1 directly with out assigning..It works for me
[HttpPost]
public ActionResult Create(StudentModel StudentEn,HttpPostedFileBase File1)
{
Student st = new Student();
//HttpPostedFileBase file;
// file = Request.Files["File1"];///it only access the name of the
//object of html."file1" is the name of the object
if (File1 != null && File1.ContentLength > 0)
{
byte[] Image=null;
Image = new byte[File1.ContentLength];
File1.InputStream.Read(Image, 0, File1.ContentLength);
StudentEn.Image=Image;
}
if (ModelState.IsValid)
{
st.Insert(StudentEn);
return RedirectToAction("Index");
}
else
{
StudentEn.STDs = getSelectedSTD(GetSTDList());
return View(StudentEn);
}
}
Try this :
public ActionResult Create(StudentModel StudentEn,FormCollection formCollection)
{
HttpPostedFileBase file= formCollection.Get("File1");
}

Save image to database with ASP.NET MVC

I am trying to save image to database with Create method. but when try this code, I get this error:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.*
I am very beginner to MVC. I will really appreciate for the response, Many thanks in advance.
[Authorize]
[HttpPost]
public ActionResult Create(Customers saveCustomer)
{
try
{
// TODO: Add insert logic here
var upload = Request.Files["ImageData"];
if (upload.ContentLength > 0)
{
string savedFileName = Path.Combine(
ConfigurationManager.AppSettings["FileUploadDirectory"],
"customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
upload.SaveAs(savedFileName);
}
_db.Customers.InsertOnSubmit(saveCustomer);
_db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Here is my create view code:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Reservation.Models.Customers>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Create</h2>
<% using (Html.BeginForm("Create", "Customers", FormMethod.Post, new {enctype="multipart/form-data"})) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Add new customer record</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.LastName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LastName) %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Email) %>
<%: Html.ValidationMessageFor(model => model.Email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Phone) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Phone) %>
<%: Html.ValidationMessageFor(model => model.Phone) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.CustomerNote) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.CustomerNote) %>
<%: Html.ValidationMessageFor(model => model.CustomerNote) %>
</div>
<div>
<input type="file" id="ImageData" name="ImageData" />
</div>
<p>
<input type="submit" value="Add recrod" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
Web.config:
<appSettings>
<add key="FileUploadDirectory" value="~/Resources/images/customers/" />
</appSettings>
Database entry:
Column Name Data Type Allow Nulls
ImageData image yes
Try this:
string savedFileName = Server.MapPath("/Resources/images/customers/" + "customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
instead of
string savedFileName = Path.Combine(
ConfigurationManager.AppSettings["FileUploadDirectory"],
"customers_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg");
If your Customer Models contains the Image field, it's not necessary to save to server-side Dirs.
the form post should not have the upload file field, please change the Controller to:
================================
[Authorize]
[HttpPost]
public ActionResult Create([Bind(Exclude = "ImageData")]Customers saveCustomer, HttpPostedFileBase ImageData)
{
try
{
// TODO: Add insert logic here
var upload = Request.Files["ImageData"];
string savedFileName = ""; //string for saving the image server-side path
if (upload.ContentLength > 0)
{
savedFileName = Server.MapPath("/Resources/images/customers/" + "customer_" + saveCustomer.FirstName + "_" + saveCustomer.LastName + ".jpg"); //get the server-side path for store image
upload.SaveAs(savedFileName); //*save the image to server-side
}
var index = savedFileName.IndexOf(#"\Resources\");
saveCustomer.ImageData = savedFileName.Substring(index, savedFileName.Length - index); //set the string of image server-side path to add-object
_db.Customers.InsertOnSubmit(saveCustomer); // save all field to databae (includes image server-side path)
_db.SubmitChanges(); // save database changes
return RedirectToAction("Index");
}
catch
{
return View();
}
}
private byte[] ImageToBytes(Image img, ImageFormat format)
{
MemoryStream mstream = new MemoryStream();
img.Save(mstream, format);
mstream.Flush();
return mstream.ToArray();
}

Creating an edit form using ASP.Net MVC 2 scaffolding

I have the following code that was generated using scaffolding and IDJefe is an int in my database, but I want the end users to choose a name from a comboBox.
How could I accomplish this?
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SeguimientoDocente.Area>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
UTEPSA | Editando Area
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Editando Area: <%: Model.Nombre %></h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Informacion Detallada de Area | <%: Model.Nombre %></legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Nombre) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Nombre) %>
<%: Html.ValidationMessageFor(model => model.Nombre) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.IDJefe) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.IDJefe) %>
<%: Html.ValidationMessageFor(model => model.IDJefe) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Volver a Listado General", "Index") %>
</div>
</asp:Content>
I've tried the following to no avail.
<%: Html.DropDownList(Model.Jefes???? %>
I could do something like this, but creating a new object for a simple thing like this seems a waste.
public ActionResult Edit(int id)
{
Area area = areaRepository.GetArea(id);
JefeRepository jefe = new JefeRepository();
ViewData["Jefes"] = new SelectList(jefe.FindAllJefes(), area.Jefe.Nombre);
return View(area);
}
Is there a better way?
You could take a look at Editor Templates. Here is an example that sounds similar to what you want to do:
http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx
Edit:
It involves creating a partial view and then using Data Annotations to call that view:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%= Html.DropDownList("",new SelectList((string[]) ViewData["Ratings"],Model)) %>

Debugging code in a view (asp.net mvc2)

How do I debug code in the View in asp.net mvc2 application?
Edit after progress last night:
Ok so now I have the following:
in Shared\EditorTemplates\Equipment.ascx :
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DAT.Models.Item>" %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<div class="editor-label">
<%: Html.Label("Item ID") %>
<%: Html.TextBoxFor(model => model.ItemID) %>
<%: Html.ValidationMessageFor(model => model.ItemID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.ModelID) %>
<%: Html.DropDownListFor(x => x.Model.Model1, new SelectList(Model.Model.Model1, "ModelId", "Model", Model.ModelID)) %>
<%: Html.ValidationMessageFor(model => model.ModelID) %>
</div>
...
in Item\Edit.aspx :
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DAT.ViewModels.ItemEditViewModel>" %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<%: Html.EditorFor(model => model.Item) %>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
The controller:
public ActionResult Edit(int id)
{
var models = from p in database.Models.Where(x => x.Model1 != null) select p;
var viewModel = new ViewModel
{
Things = database.Things.Single(a => a.ItemID == id),
//tried this:
//Models = database.Models
Models = models
};
return View(viewModel);
}
So I am sure that the problem is with this line
<%: Html.DropDownListFor(x => x.Model.Model1, new SelectList(Model.Model.Model1, "ModelId", "Model", Model.ModelID)) %>
When generating the selectlist, I don't have IEnumerable for the first parameter? Or one of the values I am feeding this is causing null. How do I get the list of models in my view?
EDIT AFTER PULLING ALL MY HAIR OUT:
It seems the problem lies in this example: http://www.asp.net/mvc/tutorials/mvc-music-store-part-4 . Strangely, I am not sure if it is following best practice. Look at the code and how they pass the models about - it seems stupidly obscure using ViewData["Blah"] and the Models as well, why can't you just have it all sent as the model? Look at the code how they have done it:
Album.ascx :
<%# Import Namespace="MvcMusicStore"%>
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMusicStore.Models.Album>" %>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<p>
<%: Html.LabelFor(model => model.Title)%>
<%: Html.TextBoxFor(model => model.Title)%>
<%: Html.ValidationMessageFor(model => model.Title)%>
</p>
<p>
<%: Html.LabelFor(model => model.Price)%>
<%: Html.TextBoxFor(model => model.Price)%>
<%: Html.ValidationMessageFor(model => model.Price)%>
</p>
<p>
<%: Html.LabelFor(model => model.AlbumArtUrl)%>
<%: Html.TextBoxFor(model => model.AlbumArtUrl)%>
<%: Html.ValidationMessageFor(model => model.AlbumArtUrl)%>
</p>
<p>
<%: Html.LabelFor(model => model.Artist)%>
<%: Html.DropDownList("ArtistId", new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.ArtistId))%>
</p>
<p>
<%: Html.LabelFor(model => model.Genre)%>
<%: Html.DropDownList("GenreId", new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.GenreId))%>
</p>
View:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.ViewModels.StoreManagerViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit - <%: Model.Album.Title %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit Album</h2>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Edit Album</legend>
<%: Html.EditorFor(model => model.Album, new { Artists = Model.Artists, Genres = Model.Genres}) %>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%:Html.ActionLink("Back to Albums", "Index") %>
</div>
</asp:Content>
View Model:
using System.Collections.Generic;
using MvcMusicStore.Models;
namespace MvcMusicStore.ViewModels
{
public class StoreManagerViewModel
{
public Album Album { get; set; }
public List<Artist> Artists { get; set; }
public List<Genre> Genres { get; set; }
}
}
And the controller:
//
// GET: /StoreManager/Edit/5
public ActionResult Edit(int id)
{
var viewModel = new StoreManagerViewModel
{
Album = storeDB.Albums.Single(a => a.AlbumId == id),
Genres = storeDB.Genres.ToList(),
Artists = storeDB.Artists.ToList()
};
return View(viewModel);
}
So it looks to me like the model is built in the controller as makes logical sense to me. Then in the view they use this statement which causes my confusion:
<%: Html.EditorFor(model => model.Album, new { Artists = Model.Artists, Genres = Model.Genres}) %>
The model is being split/changed and now we send the other (Artists, Genres) as ViewData ??
Can someone explain, and is this at all fitting with the entire design pattern?
You could put a breakpoint in your controller action and analyze your model and view data.
This being said, why are you using a strongly typed view and ViewData at the same time? Make sure that ViewData["Models"] as IEnumerable is not null (in your controller) or even better get rid of it and put it in your model as a strongly typed property. Also I would recommend you using the strongly typed helper DropDownListFor:
<%: Html.DropDownListFor(
x => x.ModelID,
new SelectList(Model.Models, "ModelId", "Model", Model.ModelID)
)%>

ForEach with EditorFor

I have got an Entity model which contains a collection of Message objects which are of the type Message which has several properties, including content, MessageID, from, and to.
I have created an EditorTemplate for type Message, however, I cannot get it to display the contents of the Messages collection.
There are no errors, but nothing is output.
Please note that the view code is from an EditorTemplate for the parent Talkback class. Can you have an EditorTemplate calling another EditorTemplate for a child collection?
Both the Talkback and Message class are generated by Entity framework from an existing database.
View code:
<% foreach (TalkbackEntityTest.Message msg in Model.Messages)
{
Html.EditorFor(x=> msg, "Message");
} %>
This is my template code. It is the standard auto-generated view code with some minor changes.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TalkbackEntityTest.Message>" %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.MessageID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.MessageID) %>
<%: Html.ValidationMessageFor(model => model.MessageID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.acad_period) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.acad_period) %>
<%: Html.ValidationMessageFor(model => model.acad_period) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.talkback_id) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.talkback_id) %>
<%: Html.ValidationMessageFor(model => model.talkback_id) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.From) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.From) %>
<%: Html.ValidationMessageFor(model => model.From) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.To) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.To) %>
<%: Html.ValidationMessageFor(model => model.To) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.SentDatetime) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.SentDatetime, String.Format("{0:g}", Model.SentDatetime)) %>
<%: Html.ValidationMessageFor(model => model.SentDatetime) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.content) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.content) %>
<%: Html.ValidationMessageFor(model => model.content) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.MessageTypeID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.MessageTypeID) %>
<%: Html.ValidationMessageFor(model => model.MessageTypeID) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
There is definitely content in the Message collection as, if I remove EditorFor and put in response.write on the content property of the Message class, I get the content field for 3 Message objects on the page, which is exactly as expected.
You don't need to foreach manually. Just put a file called Message.ascx containing the editor template you've shown inside the ~/Shared/EditorTemplates/ folder and in your view just include it:
<%: Html.EditorFor(model => model.Messages) %>

Categories

Resources