Display name in Data Entity framework - asp.net-mvc

I'd like to know how to change the display name of a model, and customize error messages in Entity Framework. I tried the following but it didn't work.
[Required(ErrorMessage = "Required .... :")]
[Display(Name = "Name Agency : ")]
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Nag
{
get
{
//code
}
set
{
//code
}
}
This is the code behind my form that adds data into my database. I've omitted irrelevant lines.
<% using (Html.BeginForm("addcar", "Agence", FormMethod.Post, new { #class = "search_form" }))
{ %>
<%: Html.ValidationSummary(true) %>
<div class="editor-label">
<%: Html.LabelFor(model => model.Dmcv) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Dmcv) %>
<%: Html.ValidationMessageFor(model => model.Dmcv) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Puisv) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Puisv) %>
<%: Html.ValidationMessageFor(model => model.Puisv) %>
</div>
// Similaire code
<p>
<input type="submit" value="Create" />
</p>
<% } %>

Change [Display(Name = "Name Agency")] to [DisplayName("Name Agency")] instead.

First you need to reference this:
using System.ComponentModel.DataAnnotations;
For changing the display name of the column, actually [Display(Name="Name Agency")] is OK. I'm using it in my projects.
For error message
[Required(ErrorMessage="Required...")]
I read that it is possible that this won't work if you are using the entity framework designer because the designer overwrites your changes over and over then you will need to use the metadatatype something like this:
[MetadataType(typeof(MetadataMyClass))]
public partial class myclass
{
}
//data annotations here
public class MetadataMyClass
{
[Required(ErrorMessage = "Required...")]
[Display(Name="Column Name")]
public global:: System.String Nag
{
// ... etc, etc...
}
}

Related

Asp.Net MVC 5 1 View 2 models with viewmodel The model item passed into the dictionary is of type error

I am new to Asp.Net MVC and I am coding a simple blog with using ASP.NET MVC 5 Framework. I can create edit and delete posts. You can see my code on GitHub in details. And I want to add comment property to Details page of every posts or articles. I spent so much time for this and tried several ways. I am trying to make it with using ViewModel Here is my code.
CommentVM:
public DateTime Date { get; set; }
public string CommentContent { get; set; }
public Article articles { get; set; }
public List<Comment> commentList { get; set; }// to show comments which is written before.
Details View:(I modified Details page of Articles. it was #model Blog.Models.Comment I turned to CommentVM and added model.articles.Title. So there is no error in Visual Studio.)
#model Blog.Models.CommentVM
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Article</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.articles.Title)
</dt>
<dd>
#Html.DisplayFor(model => model.articles.Title)
</dd>
.
.
.
</dl>
</div>
<div class="jumbotron">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="col-md-10">
#Html.EditorFor(model => model.CommentContent, new { htmlAttributes = new { #class = "form-control" } })
</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>
Of course this code is not enough. First of all I should write a controller for this. Default controller for this Details page is this:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Article article = db.Articles.Find(id);
if (article == null)
{
return HttpNotFound();
}
return View(article);
}
How will I change this Controller Method and View to create and show comments under articles? If you recommend good ViewModel tutorial, I will appretiate this. I want 3 things in Details page 1) Details of an article 2) Create comment 3) show under this comment as in forums or any blog. Please help
You should create a partial view for showing the comments, the model of that view being List<Comment> for displaying the list of comments.
For adding a new comment also can be done using a partial view which will have Comment as the model
Or you can follow the method mentioned in this post
CSHTML
<% using (Html.BeginForm(new { Action = "AddComment", postId = Model._id}))
{ %>
<h2>Title: <%= Model.Title%> </h2>
<%= Model.Body%>
<h3>Comments</h3>
<% if(Model.Comments.Count > 0)
{ %>
<% foreach (var comment in Model.Comments)
{ %>
Name: <%= comment.Name %>
Comment: <%= comment.Text %>
<% } %>
<%
}%>
<h4>Enter Comments</h4>
Name: <%= Html.TextBox("Name")%>
Comment: <%= Html.TextArea("Text")%>
<input type="submit" value="Submit" />
<% } %>

Post parameter is null

I Have controller with following methods:
public ActionResult Create()
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult Create(Tests test)
{
test.CreateDate = DateTime.Now;
test.Author = User.Identity.Name;
TestEntities db = new TestEntities();
db.AddToTests(test);
db.SaveChanges();
return RedirectToAction("CreateQuestion", new { OrderNumber = 1, idTest = test.id });
}
[Authorize]
public ActionResult CreateQuestion(int OrderNumber,int idTest)
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult CreateQuestion(Questions question)
{
TestEntities db = new TestEntities();
db.AddToQuestions(question);
db.SaveChanges();
return RedirectToAction("CreateQuestion", new {id = question.id, t = question.Type});
}
The problem is Create methods works right. It get parameter and adds it to DB. But similar method CreateQuestion displays message about question is null.
What do I wrong?
CreateQuestion view
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<test.su.Models.Questions>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Создать вопрос
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Создать вопрос</h2>
<% using (Html.BeginForm("CreateQuestion","Test")) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Вопрос</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Type,"Тип вопроса") %>
</div>
<% // List of question types
List<SelectListItem> QuestionTypes = new List<SelectListItem>();
SelectListItem t = new SelectListItem();
t.Text = "Вопрос с вариантами ответа (флажки или радиокнопки)";
t.Value = "0";
QuestionTypes.Add(t);
t = new SelectListItem();
t.Text = "Вопрос со свободным ответом (текстовое поле)";
t.Value = "1";
QuestionTypes.Add(t);
%>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Type, QuestionTypes) %>
<%: Html.ValidationMessageFor(model => model.Type) %>
</div>
<%-- <div class="editor-label">
<%: Html.LabelFor(model => model.OrderNumber,"Порядковый номер вопроса") %>
<%: Html.EditorFor(model => model.OrderNumber) %>
<%: Html.ValidationMessageFor(model => model.OrderNumber) %>
</div>--%>
<div class="editor-label">
<%: Html.LabelFor(model => model.Question,"Текст вопроса") %>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(model => model.Question,2,47,"") %>
<%: Html.ValidationMessageFor(model => model.Question) %>
</div>
<%: Html.HiddenFor(model => model.idTest) %>
<%: Html.ValidationMessageFor(model => model.idTest) %>
<%: Html.HiddenFor(model => model.OrderNumber ) %>
<%: Html.ValidationMessageFor( model => model.OrderNumber) %>
<p>
<input type="submit" value="Далее" />
</p>
</fieldset>
<% } %>
</asp:Content>
This is difficult to figure out without knowing the model. Someone else may provide a better answer, but here is the only thing I can think of for now:
If your Questions model looks like this:
public class Questions
{
int Id {get;set;}
string Name {get;set;}
string Description {get;set;}
}
What you can do, for now, is alter your controller to accept the individual parameters and create the object yourself. This might help you figure out which critical property in your Model is missing.
public ActionResult CreateQuestion(string Name, string Description)
{
//make the entity yourself
Questions newQuestion = new Questions()
{
Name = Name,
Description = Description
}
//your other code here
}
Now normally MVC is smart enough to bind your individual values in your form (view) to your model, but some critical value is missing and causing you issue. Once you've figured out what that is, you can actually restore your controller back to accepting only a Questions object.
Sorry I couldn't help you more.
Good Luck.

DropDownListFor not binding on Edit View with repeating items (List<T>)

Here is the thing. I have an Edit view, which doesnt bind the dropdowns' value when I open it.
[NonAction]
public List<SelectListItem> VraagType() {
List<SelectListItem> l = new List<SelectListItem>();
SelectListItem a = new SelectListItem();
SelectListItem b = new SelectListItem();
a.Text = "Meerkeuze";
a.Value = "M";
b.Text = "Open";
b.Value = "O";
l.Add(a);
l.Add(b);
return l;
}
[NonAction]
public List<SelectListItem> getSchalen() {
return _db.EvalSchaals.ToList().ToSelectList(q => q.Sch_Naam, q => q.Sch_ID.ToString(), q => q.Sch_ID == -1).ToList();
}
public ActionResult Edit(int id) {
ViewData["vraagtype"] = VraagType();
ViewData["schaal"] = getSchalen();
EvalVragenBlok evb = _db.EvalVragenBloks.First(q => q.Vrbl_ID == id);
List<EvalVragen> ev = _db.EvalVragens.Where(q => q.Vrbl_ID == id).ToList();
FlatEvalVragenBlok fevb = Mapper.Map<EvalVragenBlok, FlatEvalVragenBlok>(evb);
fevb.Vragen = new List<FlatEvalVragen>();
return View(fevb);
}
this is the code from the controller.
here is the code from the Edit.aspx view
<h2>
Edit</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Vrbl_Titel) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Vrbl_Titel) %>
<%: Html.ValidationMessageFor(model => model.Vrbl_Titel) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Sch_ID) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Sch_ID, ViewData["schaal"] as List<SelectListItem>, "Selecteer een schaal...") %>
<%: Html.ValidationMessageFor(model => model.Sch_ID) %>
</div>
<%= Html.ValidationMessageFor(model => model.Vragen) %>
<table id="vragentbl">
<tr>
<th>
</th>
<th>
Vraag
</th>
<th>
Soort
</th>
</tr>
<% if (Model.Vragen != null) { %>
<% for (int i = 0; i < Model.Vragen.Count; i++) { %>
<tr>
<td>
<%=i + 1%>
</td>
<td>
<%= Html.TextBoxFor(model => model.Vragen[i].Evvr_Vraag, new { style = "width:400px" })%><br />
<%= Html.ValidationMessageFor(model => model.Vragen[i].Evvr_Vraag)%>
</td>
<td>
<%= Html.DropDownListFor(model => model.Vragen[i].Evvr_Type, ViewData["vraagtype"] as List<SelectListItem>, new { style = "width:95px" })%><br />
<%= Html.ValidationMessageFor(model => model.Vragen[i].Evvr_Type)%>
</td>
</tr>
<% }
} %>
<tr>
<td>
</td>
<td>
<a id="addnew" href="#">Voeg extra keuze toe</a>
</td>
<td>
</td>
</tr>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
I have 2 List 's. 1 of them is in the non-repeating part of the form (Schalen), the other one (VraagType) is Inside the repeating part.
for Schalen, everything works fine. i open the edit view, and all fields are filled in like it should be. the Vrbl_Titel has its value, and the dropdown of Sch_ID has the value it received from the object which i sent with the view, which came from the DB.
The problem lies in the repeating part.
the textbox for model.Vragen[i].Evvr_Vraag get's its value, and the dropdown for model.Vragen[i].Evvr_Type is shown, however, this dropdown does not get the value which was sent in the object. it keeps it's default standard value, which is the first item in the 'selectlist'
how do i get my value from my 'Vragen' object, into the dropdown. if i put the value in a simple textbox
<%= Html.TextBoxFor(model => model.Vragen[i].Evvr_Type)%>
then the textbox does get the value. so the problem is that the dropdownvalue doesnt change form it's initial value... bug in MVC?
just for info, this is how the object(s) look sent to the view:
namespace MVC2_NASTEST.Models {
public partial class FlatEvalVragenBlok {
public int Vrbl_ID { get; set; }
public int Sch_ID { get; set; }
public string Vrbl_Titel { get; set; }
public List<FlatEvalVragen> Vragen { get; set; }
}
}
namespace MVC2_NASTEST.Models {
public partial class FlatEvalVragen {
public int Evvr_ID { get; set; }
public int Vrbl_ID { get; set; }
public int Evvr_rang { get; set; }
public string Evvr_Vraag { get; set; }
public char Evvr_Type { get; set; }
}
}
It seems this is really a bug or at least inconsistency in ASP.NET MVC 2. I have examined its source and found what InputHelper() method called from TextBoxFor() helper receives default value calculated with
ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model
But SelectInternal() method called from DropDownListFor() helper receives only a name of a control found with ExpressionHelper.GetExpressionText() method.
So SelectInternal() tries to find default value using ViewData.Eval() method from MVC 1. It's known what this method isn't able to extract values from arrays by numeric index.
So in your case are applicable
<%: Html.DropDownListFor(model => model.Sch_ID) %>
<%= Html.TextBoxFor(model => model.Vragen[i].Evvr_Type)%>
but not
<%: Html.DropDownListFor(model => model.Vragen[i].Evvr_Type) %>
because it's equivalent to
<%: Html.DropDownList("Vragen[" + i + "].Evvr_Type") %>
At the same time I want to emphasize again what
<%= Html.TextBoxFor(model => model.Vragen[i].Evvr_Type)%>
isn't equivalent to
<%= Html.TextBox("model.Vragen[" + i + "].Evvr_Type")%>
because latter even in MVC 2 can't bind default value.
Possible workarounds
First. Since SelectInternal() also checks ModelState dictionary you can fill this dictionary before returning the view.
for (int i=0; i < fevb.Vragen.Count(); i++)
ModelState.Add("Vragen[" + i + "].Evvr_Type", new ModelState
{
Value = new ValueProviderResult(fevb.Vragen[i].Evvr_Type, null,
CultureInfo.CurrentCulture)
});
This will be done by MVC itself after from post, so you should do it manually only first time.
Second. Instead of
<%= Html.DropDownListFor(model => model.Vragen[i].Evvr_Type,
ViewData["vraagtype"] as List<SelectListItem>)%>
use
<%= Html.DropDownListFor(model => model.Vragen[i].Evvr_Type,
new SelectList(ViewData["vraagtype"] as IEnumerable, "Value", "Text",
Model.Vragen[i].Evvr_Type))%>
ViewData["vraagtype"] in this case doesn't have to contain objects of SelectListItem, any IEnumerable is enough. You may check SelectList() method description in case of need.

Create view is posting null objects

Should be an easy question to answer.
I am trying to create an object in a view. The class that contains the object consists of a User class and a password.
When I click on the submit button, the Controller picks up null values for Password and User.
See below the Container class, the Controller and the View;
public class UserExtended
{
public UserITOC User { get; set; }
public string Password { get; set; }
}
[Authorize]
public ActionResult Create()
{
return View(new UserExtended());
}
//
// POST: /Dinners/Create
[Authorize(Roles = "Administrator")]
[HttpPost]
public ActionResult Create(UserExtended user)
{
if (ModelState.IsValid)
{
// Create user in the User datatable
SqlUsersRepository sqlRepository = new SqlUsersRepository();
ITOCEntities db = new ITOCEntities();
db.UserITOCs.AddObject(user.User);
// Create user as an authenticated user within the Reader role.
int i = user.User.EmailAddress.IndexOf('#') - 1;
string userName = user.User.EmailAddress.Substring(0, i);
string email = user.User.EmailAddress;
Membership.CreateUser(userName, user.Password, email);
Roles.AddUserToRole(userName, "Reader"); // Automatically assigned as a Reader
}
return View(new UserExtended());
}
" %>
Create
<h2>Create</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.User.Forename) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.User.Forename)%>
<%: Html.ValidationMessageFor(model => model.User.Forename)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.User.Surname) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.User.Surname)%>
<%: Html.ValidationMessageFor(model => model.User.Surname)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.User.EmailAddress) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.User.EmailAddress)%>
<%: Html.ValidationMessageFor(model => model.User.EmailAddress)%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Password) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Password)%>
<%: Html.ValidationMessageFor(model => model.Password) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
Extremely simple solution:
Change your action-signature from
public ActionResult Create(UserExtended user)
to
public ActionResult Create(UserExtended UserExtended)
That way the ModelBinder will know how to reassemble the object from Request.
Hope this helps!
I had a very similar problem, but found in my case that I had to match the database table name rather than the type name
Name of the type: NonTradingDay
Database table name: dbo.NonTradingDays (had been pluralized)
Create Method:
[HttpPost]
public ActionResult Create(NonTradingDay NonTradingDays)
{
if (ModelState.IsValid)
{
db.NonTradingDay.Add(NonTradingDays);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(NonTradingDays);
}
I had tried 'NonTradingDay', but still got null; I then looked at the database table name, tried 'NonTradingDays' and the mapping was made (the argument was no longer null).
I think this was because I had the database context as:
public DbSet<NonTradingDay> NonTradingDay { get; set; }
Rather than:
public DbSet<NonTradingDay> NonTradingDays { get; set; }
you are returning a new instance of UserExtended class
return View(new UserExtended());
instead return the object you get as the parameter
return user

ASP.NET MVC File Upload Error - "The input is not a valid Base-64 string"

I'm trying to add a file upload control to my ASP.NET MVC 2 form but after I select a jpg and click Save, it gives the following 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.
Here's the view:
<% using (Html.BeginForm("Save", "Developers", FormMethod.Post, new {enctype = "multipart/form-data"})) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
Login Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LoginName) %>
<%: Html.ValidationMessageFor(model => model.LoginName) %>
</div>
<div class="editor-label">
Password
</div>
<div class="editor-field">
<%: Html.Password("Password") %>
<%: Html.ValidationMessageFor(model => model.Password) %>
</div>
<div class="editor-label">
First Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div class="editor-label">
Last Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LastName) %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<div class="editor-label">
Photo
</div>
<div class="editor-field">
<input id="Photo" name="Photo" type="file" />
</div>
<p>
<%: Html.Hidden("DeveloperID") %>
<%: Html.Hidden("CreateDate") %>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
And the controller:
//POST: /Secure/Developers/Save/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Developer developer)
{
//get profile photo.
var upload = Request.Files["Photo"];
if (upload.ContentLength > 0)
{
string savedFileName = Path.Combine(
ConfigurationManager.AppSettings["FileUploadDirectory"],
"Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg");
upload.SaveAs(savedFileName);
}
developer.UpdateDate = DateTime.Now;
if (developer.DeveloperID == 0)
{//inserting new developer.
DataContext.DeveloperData.Insert(developer);
}
else
{//attaching existing developer.
DataContext.DeveloperData.Attach(developer);
}
//save changes.
DataContext.SaveChanges();
//redirect to developer list.
return RedirectToAction("Index");
}
Thanks,
Justin
I have recently found a solution for this, although I am now using MVC3 rather than MVC2.
In the Save action, exclude the binary field from the bound object and include a separate HttpPostedFileBase field:
e.g.
public ActionResult Save([Bind(Exclude = "Photo")]Developer developer, HttpPostedFileBase Photo) {...}
Note that you can also do this to avoid having to include the Html.Hidden elements from your View. e.g.:
public ActionResult Save([Bind(Exclude = "Photo,DeveloperID,CreateDate")]Developer developer, HttpPostedFileBase Photo) {...}
You can then use this HttpPostedFileBase object directly rather than needing to access Request.Files.
Personally, I actually store these types of images in the database in an SQL "image" field using this code:
if (Picture != null)
{
if (Picture.ContentLength > 0)
{
byte[] imgBinaryData = new byte[Picture.ContentLength];
int readresult = Picture.InputStream.Read(imgBinaryData, 0, Picture.ContentLength);
Developer.Picture = imgBinaryData;
}
}
Hope this is helpful...
Mark
I just tried your code and was able to upload without any issues. I did not save to the database nor does my Developer class have a Photo property.
namespace MvcApplication5.Controllers
{
public class Developer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime UpdateDate { get; set; }
public int DeveloperID { get; set; }
public string LoginName { get; set; }
public string Password { get; set; }
}
}
Controller
public class DefaultController : Controller
{
//
// GET: /Default/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Developer developer)
{
//get profile photo.
var upload = Request.Files["Photo"];
if (upload.ContentLength > 0)
{
string savedFileName = Path.Combine(
#"C:\temp",
"Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg");
upload.SaveAs(savedFileName);
}
developer.UpdateDate = DateTime.Now;
if (developer.DeveloperID == 0)
{//inserting new developer.
}
else
{//attaching existing developer.
}
//save changes.
//redirect to developer list.
return RedirectToAction("Index");
}
}
View
<div>
<% using (Html.BeginForm("Save", "Default", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<%: Html.ValidationSummary(true)%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
Login Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LoginName)%>
<%: Html.ValidationMessageFor(model => model.LoginName)%>
</div>
<div class="editor-label">
Password
</div>
<div class="editor-field">
<%: Html.Password("Password")%>
<%: Html.ValidationMessageFor(model => model.Password)%>
</div>
<div class="editor-label">
First Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName)%>
<%: Html.ValidationMessageFor(model => model.FirstName)%>
</div>
<div class="editor-label">
Last Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LastName)%>
<%: Html.ValidationMessageFor(model => model.LastName)%>
</div>
<div class="editor-label">
Photo
</div>
<div class="editor-field">
<input id="Photo" name="Photo" type="file" />
</div>
<p>
<%: Html.Hidden("DeveloperID")%>
<%: Html.Hidden("CreateDate")%>
<input type="submit" value="Save" />
</p>
</fieldset>
<%} %>
</div>
I got the same issue. here is the solution I found.
Class property:
public byte[] Logo { get; set; }
View Code:
#using (Html.BeginForm("StoreMyCompany", "MyCompany", FormMethod.Post, new { id = "formMyCompany", enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.modelMyCompany.Logo, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
<input type="file" name="Logo" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
</div>
</div>
}
Controller Code:
public ActionResult StoreMyCompany([Bind(Exclude = "Logo")]MyCompanyVM model)
{
try
{
Company objCompany = new Company();
byte[] imageData = null;
if (Request.Files.Count > 0)
{
HttpPostedFileBase objFiles = Request.Files["Logo"];
using (var binaryReader = new BinaryReader(objFiles.InputStream))
{
imageData = binaryReader.ReadBytes(objFiles.ContentLength);
}
}
}
catch (Exception ex)
{
Utility.LogError(ex);
}
return View();
}
}
i just excluded Logo from controller's call.
I have the same error, but the solution above didn't work for me, instead I notice that my Model property name is the same as the parameter name I am passing with the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditSOP(File file, HttpPostedFileBase Upload)
My Model property name is
public byte[] Upload { get; set; }
After renaming it on a different parameter name, it now works:
public ActionResult EditSOP(File file, HttpPostedFileBase UploadFile)

Resources