asp.net mvc tinymce usage? - asp.net-mvc

scripts
<script type="text/javascript">
tinyMCE.init({
language: "tr",
elements: "Body",
mode: "exact",
height: 400,
width: 600
});
</script>
<script>
$(function () {
$('#form_post').ajaxForm({
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});
</script>
html
#using (Html.BeginForm("_AddPost", "Posts", FormMethod.Post, new { id = "form_post" }))
{
<div class="editor-label">
<input type="file" name="File" id="File" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PostTypeId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.PostTypeId, ViewBag.PostTypes as SelectList, "--- Haber Tipi ---", new { #class = "custom_select" })
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.PostTypeId)
</div>
...
<div class="editor-label">
#Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Body, new { #class = "custom_textarea" })
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.Body)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AuthorId)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.AuthorId, ViewBag.Authors as SelectList, "--- Yazarlar ---", new { #class = "custom_select" })
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.AuthorId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsActive)
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.IsActive)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.IsActive)
</div>
<div class="submit-field">
<input type="submit" value="Ekle" class="button_gray" />
</div>
}
model
public class PostViewModel
{
public int Id { get; set; }
...
[Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
[Display(Name = "Haber İçerik")]
[AllowHtml]
public string Body { get; set; }
...
[Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
[Display(Name = "Haber Tipi")]
public Nullable<int> PostTypeId { get; set; }
[Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
[Display(Name = "Yazar")]
public Nullable<int> AuthorId { get; set; }
[Display(Name = "Kategori")]
public Nullable<int> CategoryId { get; set; }
...
[Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
[Display(Name = "Yayında")]
[DefaultValue(true)]
public bool IsActive { get { return true; } set { } }
public HttpPostedFileBase File { get; set; }
}
when I post view tinymce editor content,it does not bind to model property. Other properties bind, ony tinymce not.
I mean in controller action
model.Title // is my expected
model.Description // is my expected
model.Body // null
controller
public ActionResult _AddPost()
{
using (NewsCMSEntities entity = new NewsCMSEntities())
{
// following lines are true. I can see dropdownlist values...
ViewBag.PostTypes = new SelectList(entity.PostTypes.ToList(), "Id", "Name");
ViewBag.Authors = new SelectList(entity.Authors.ToList(), "Id", "Name");
ViewBag.Categories = new SelectList(entity.Categories.ToList(), "Id", "Name");
return PartialView(new PostViewModel());
}
}
[HttpPost]
public ActionResult _AddPost(PostViewModel viewModel)
{
Posts post = new Posts();
post = AutoMapper.Mapper.Map<PostViewModel, Posts>(viewModel);
PostImages postImage = new PostImages();
HttpPostedFileBase file = viewModel.File;
using (NewsCMSEntities entity = new NewsCMSEntities())
{
if (ModelState.IsValid)
{
// add post to db
}
else
{
foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
Console.WriteLine(error);
// error message model.Body is null
}
}
}
All model properties are my expected only Body property is not. What am I missing?
Thanks...

The trick with TinyMCE is that it replaces the textarea with an iframe. In case of standard POST, the TinyMCE handles the updating of the original textarea by itself, but when you put AJAX into play you need to do it by yourself. It can be done in beforeSerialize callback of jQuery Form Plugin which you are using:
$(function () {
$('#form_post').ajaxForm({
beforeSerialize: function($form, options) { tinyMCE.triggerSave(); },
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});

Related

POST Method doesn't work MVC 4

I try Create a new article in my table art, but the POST Method doesn't work, i don't now why, , Edit Article working perfectly, i read many post form that topic and nothing, i hope anyone can help me
Model
public class Art
{
[Key]
public int idArt { get; set; }
[DisplayName("Codigo Artículo")]
[Required(ErrorMessage = "Codigo Artículo Requerido")]
[MaxLength(30)]
public string co_art { get; set; }
[DisplayName("Tipo Articulo")]
[ForeignKey("TypeArticles")]
[Required(ErrorMessage = "Tipo Artículo Requerido")]
public int IDType { get; set; }
public virtual TypeArticles TypeArticles { get; set; }
[DisplayName("Descripción")]
[Required(ErrorMessage = "Descripción Artículo Requerido")]
[MaxLength(150)]
public string des_art { get; set; }
[DisplayName("Modelo")]
[Required(ErrorMessage = "Modelo Artículo Requerido")]
[MaxLength(50)]
public string modelo { get; set; }
[DisplayName("Referencia")]
[MaxLength(50)]
[Required(ErrorMessage = "Referencia Artículo Requerido")]
public string referencia { get; set; }
[DisplayName("Linea Artículo")]
[ForeignKey("Linea")]
[Required(ErrorMessage = "Linea Artículo Requerido")]
public int IdLinea { get; set; }
public virtual Linea Linea { get; set; }
[DisplayName("Categoria Artículo")]
[ForeignKey("Categoria")]
[Required(ErrorMessage = "Categoria Artículo Requerido")]
public int idCat { get; set; }
public virtual Categoria Categoria { get; set; }
[DisplayName("Precio Venta")]
[Range(0.01, 999999999, ErrorMessage = "Precio debe estar entre 0.01 y 999999999")]
public double Price { get; set; }
[MaxLength(1024)]
[DisplayName("Info. Adicional")]
public string Adicional { get; set; }
[MaxLength(100)]
public string Photo { get; set; }
}
Controller POST Method
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Art artmodels)
{
ViewBag.idLinea = new SelectList(db.Linea.OrderBy(c => c.des_lin), "IdLinea", "des_lin");
ViewBag.IdCat = new SelectList(db.Categorias.OrderBy(c => c.des_cat), "IdCat", "des_cat");
ViewBag.IDType = new SelectList(db.TypeArticles.OrderBy(c => c.TypeDesc), "IDType", "TypeDesc");
if (ModelState.IsValid)
{
var art_exists = (from inv in db.Art where inv.co_art == artmodels.co_art.Trim() select inv).FirstOrDefault();
if (art_exists != null)
{
ModelState.AddModelError("co_art", "Codigo de Articulo ya Existe");
return View(artmodels);
}
db.Art.Add(artmodels);
db.SaveChanges();
///
//int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
//var articulos = db.Art;
//IPagedList<Art> art_paged = null;
//art_paged = articulos.OrderBy(i => i.co_art).ToPagedList(currentPageIndex, (pagesize.HasValue) ? pagesize.Value : defaultPageSize);
return RedirectToAction("Edit", "Articulos", new {id = artmodels.idArt });
}
this.Response.StatusCode = 400;
return View(artmodels);
}
View
#model mvcAmerica.Models.Art
#{
ViewBag.Title = "Creacion";
}
<h1><small>Creación Articulos</small></h1>
#using (Html.BeginForm("Create", "Articulos", FormMethod.Post))
{
#Html.ValidationSummary(true)
<text>
#{Html.RenderPartial("CreateOrEditArticulos", Model);}
</text>
}
RenderPartial
#model mvcAmerica.Models.Art
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
#Html.HiddenFor(model => model.idArt)
<div class="clearfix">
#Html.LabelFor(model => model.co_art)
<div class="input">
#Html.EditorFor(model => model.co_art)
#Html.ValidationMessageFor(model => model.co_art)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.des_art)
<div class="input">
#Html.EditorFor(model => model.des_art)
#Html.ValidationMessageFor(model => model.des_art)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.IDType, "Tipo Articulo")
<div class="input chosen-select">
#Html.DropDownList("IDType", String.Empty)
#Html.ValidationMessageFor(model => model.IDType)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.modelo)
<div class="input">
#Html.EditorFor(model => model.modelo)
#Html.ValidationMessageFor(model => model.modelo)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.referencia)
<div class="input">
#Html.EditorFor(model => model.referencia)
#Html.ValidationMessageFor(model => model.referencia)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.IdLinea)
<div class="input chosen-select">
#Html.DropDownList("IdLinea", String.Empty)
#Html.ValidationMessageFor(model => model.IdLinea)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.idCat)
<div class="input chosen-select">
#Html.DropDownList("IdCat", String.Empty)
#Html.ValidationMessageFor(model => model.idCat)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.Price)
<div class="input">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.Adicional)
<div class="input">
#Html.EditorFor(model => model.Adicional)
#Html.ValidationMessageFor(model => model.Adicional)
</div>
</div>
<div class="actions">
<input type="submit" class="btn primary" value="Guardar" />
#Html.ActionLink("Listado", "Index", null, new { #class = "btn" })
</div>
</fieldset>
}
Thanks for the help that bring me in this problem...
You have nested forms in your code which is causing this issue. The Submit button is in the inner but it dies not have any Controller and Anction methods to call, So it's not post the data to any method.
So you need to change this code something like this:
View
#model mvcAmerica.Models.Art
#{
ViewBag.Title = "Creacion";
}
<h1><small>Creación Articulos</small></h1>
//the commented line should go to the partial view
//#using (Html.BeginForm("Create", "Articulos", FormMethod.Post))
//{
// #Html.ValidationSummary(true)
<text>
#{Html.RenderPartial("CreateOrEditArticulos", Model);}
</text>
RenderPartial
#model mvcAmerica.Models.Art
#using (Html.BeginForm("Create", "Articulos", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
// rest of the code is as it is
}

ASP Net MVC - Forms Validation on the ViewModel

I have a form which has a ViewModel class underlaying it. I have set the [Required] validation on fields of the form. The form still submits even though it does for a moment - before it submits - displays the ErrorMessage set on particular fields.
There is no validation on the StockReceipt model itself, but only the ViewModel. I looked at this question here and learnt that validating the model is optional.
I wonder why the form still submits when there are invalid input?
Here is my View and ViewModel code:
View:
#using (Html.BeginForm("SaveSettings", "StockReceipt", FormMethod.Post,
new { id = "StockReceiptForm", enctype = "multipart/form-data" }))
{
<fieldset>
<div>
#* #Html.ValidationSummary(false)*#
<legend>Stock-Receipt Details</legend>
#*#if (User.IsInRole(Constants.Super))
{*#
<div style="display: none;">
Delivery Note Ref
</div>
<div style="display: none;">
#Html.TextBoxFor(model => model.StockReceiptID, new { #Class = "k-textbox" })
</div>
<div class="editor-label">
Supplier
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.SupplierID).BindTo(Model.SuppliersList).DataTextField("Name").DataValueField("SupplierID").OptionLabel("Select")
#Html.ValidationMessageFor(model => model.SupplierID)
</div>
<div class="editor-label">
Material
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.MaterialID).BindTo(Model.MaterialsList).DataTextField("Name").DataValueField("MaterialID").OptionLabel("Select")
#Html.ValidationMessageFor(model => model.MaterialID)
</div>
<div class="editor-label">
Qty
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Quantity, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.Quantity)
</div>
<div class="editor-label">
Of which reserved
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.QuantityReserved, new { #Class = "k-textbox" })
</div>
<div class="editor-label">
Units
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.NumberOfUnits, new { #Class = "k-textbox" })
#(Html.Kendo().DropDownListFor(model => model.StockUnitsEnum).Name("StockUnitsEnum")
.BindTo(Enum.GetValues(typeof(StockUnitsEnum))
.Cast<StockUnitsEnum>()
.Select(p => new SelectListItem
{
Text = p.ToString(),
Value = ((int)p).ToString(CultureInfo.InvariantCulture)
})
.ToList())
)
#Html.ValidationMessageFor(model => model.NumberOfUnits)
</div>
<div class="editor-label">
Batch Reference:
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.BatchReference, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.BatchReference)
</div>
<div class="editor-label">
Slab Width
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.SlabWidth, new { #Class = "k-textbox" }) x #Html.TextBoxFor(model => model.SlabHeight, new { #Class = "k-textbox" })
</div>
<div class="editor-label">
Include Transport:
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.IncludeTransport)
</div>
<div class="editor-label">
Notes
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Notes, new { #Class = "k-textbox" })
</div>
<div class="clear">
Totals
</div>
<div class="editor-label">
Unit Cost
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.UnitCost, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.UnitCost)
</div>
<div class="editor-label">
Units
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.NumberOfUnits, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.NumberOfUnits)
</div>
<div class="editor-label">
Slab Cost
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.SlabCost, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.SlabCost)
</div>
<div class="editor-label">
Location
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.LocationID).BindTo(Model.LocationsList).DataTextField("Name").DataValueField("LocationID").OptionLabel("Select")
</div>
<div class="editor-label">
Purchase-Order Ref.
</div>
<div class="editor-field">
#Html.Kendo().DropDownListFor(model => model.PurchaseOrderID).BindTo(Model.PurchaseOrdersList).DataTextField("PONumber").DataValueField("PurchaseOrderID").OptionLabel("Select")
#Html.ValidationMessageFor(model => model.PurchaseOrdersList)
</div>
<div class="editor-label">
Invoice Ref.
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.InvoicNo, new { #Class = "k-textbox" })
#Html.ValidationMessageFor(model => model.InvoicNo)
</div>
<br />
<div class="editor-label">
</div>
<div class="editor-field">
<input type="submit" value="Save" class="k-button" />
</div>
</div>
</fieldset>
}
ViewModel:
public class StockReceiptViewModel
{
public int StockReceiptID { get; set; }
[Required(ErrorMessage = "Required")]
public int SupplierID { get; set; }
[Required(ErrorMessage = "Required")]
public int MaterialID { get; set; }
[Required(ErrorMessage = "Required")]
public DateTime? ReceiptDate { get; set; }
[Required(ErrorMessage = "Required")]
public int Quantity { get; set; }
public int? QuantityReserved { get; set; }
[Required(ErrorMessage = "Required")]
public decimal? SlabWidth { get; set; }
[Required(ErrorMessage = "Required")]
public decimal? SlabHeight { get; set; }
[Required(ErrorMessage = "Required")]
public int SizeUnits { get; set; }
[Required(ErrorMessage = "Required")]
public StockUnitsEnum StockUnitsEnum
{
get {return (StockUnitsEnum)SizeUnits;}
set {SizeUnits = (int)value;}
}
[Required(ErrorMessage = "Required")]
public string BatchReference { get; set; }
[Required(ErrorMessage = "Required")]
[DataType(DataType.Currency)]
public decimal? UnitCost { get; set; }
[Required(ErrorMessage = "Required")]
public int? NumberOfUnits { get; set; }
[Required(ErrorMessage = "Required.")]
public int PurchaseOrderID { get; set; }
[Required(ErrorMessage = "Required")]
public string InvoicNo { get; set; }
[Required(ErrorMessage = "Required")]
public decimal SlabCost { get; set; }
public bool IncludeTransport { get; set; }
[Required(ErrorMessage = "Required.")]
public int LocationID { get; set; }
public int? EnteredBy { get; set; }
public DateTime OnSystemFrom { get; set; }
public string Notes { get; set; }
public List<SupplierViewModel> SuppliersList { get; set; }
public List<MaterialViewModel> MaterialsList { get; set; }
public List<LocationsViewModel> LocationsList { get; set; }
public List<PurchaseOrderViewModel> PurchaseOrdersList { get; set; }
public int LastModifiedBy { get; set; }
public DateTime LastModifiedDate { get; set; }
public int LiveQuantity { get; set; }
}
The Controller method has the ModelState.Isvalid check as well.
Please help if you can.
Many thanks.
You need to add jquery.unobtrusive and jquery.validate files to your views. Add this to your BundleConfig.cs:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
And then render it on your _Layout View or in View you want validation:
#Scripts.Render("~/bundles/jqueryval")
If you are using default MVC template you should already have this bundle. Just make sure you have reference in your Views. You can check if your js files are loaded by using some web development tools like Firebug in Mozzila or press F12 in Chrome, and in NET tab you can see loaded scripts.
I have solved this problem by making sure that the method to where this form is submitting, is returning the viewmodel to the page (view) if ModelState.IsValid is false.
This is provided that the viewModel being returned is actually the same as the submitted one:
[HttpPost]
public ActionResult SaveSettings(StockReceiptViewModel stockReceiptVm)
{
try
{
if (ModelState.IsValid)
{
var stockReceipt = new StockReceipt();
if (stockReceiptVm.StockReceiptID != 0)
{
MapViewModelToModel(stockReceiptVm, stockReceipt);
stockReceipt.LastModifiedBy = UserHelper.GetCurrentUserIDByEmail();
stockReceipt.LastModifiedDate = DateTime.Now;
//update
_stockReceiptRepository.UpdateStockReceipt(stockReceipt, stockReceiptVm.StockReceiptID);
}
else
{
MapViewModelToModel(stockReceiptVm, stockReceipt);
stockReceipt.EnteredBy = UserHelper.GetCurrentUserIDByEmail();
stockReceipt.OnSystemFrom = Utilities.RemoveTimeFromDate(DateTime.Now);
//save new
_stockReceiptRepository.InsertStockReceipt(stockReceipt);
}
return RedirectToAction("Index", "StockReceiptsGrid");
}
SetupViewDropdownLists(stockReceiptVm);
return View("Index", stockReceiptVm);
}
catch (Exception exc)
{
ErrorHelper.WriteToEventLog(exc);
return RedirectToAction("Index", "Error");
}
}

ASP.NET MVC: Values are null when they reach the Controller

So I have the following Controller:
[HttpPost]
public ActionResult CreateSupport(CreateSupport model)
{
if (ModelState.IsValid && (model.Description != null))
{
model.CreatedById = UserId;
model.ModifiedById = UserId;
}
return View(model);
}
I have the following view:
#using (Html.BeginForm("CreateSupport", "Support", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-label">
#Html.LabelFor(model => model.Subject, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Subject)
#Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="support-form-left">
<div class="editor-label">
#Html.LabelFor(model => model.BrowserInfo, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.BrowserInfo)
#Html.ValidationMessageFor(model => model.BrowserInfo)
</div>
</div>
<div class="support-form-right">
<div class="editor-label">
#Html.LabelFor(model => model.DatabaseVersion, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.DatabaseVersion)
#Html.ValidationMessageFor(model => model.DatabaseVersion)
</div>
</div>
<div class="clearFloat"></div>
<div class="editor-label">
#Html.LabelFor(model => model.Description, new Dictionary<string, object>() { { "class", "req" } })
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="actionButtons">
<button id="btnCancel" class="myButtonCancel">Cancel</button>
<input type="submit" value="Submit" class="myButton" />
</div>
#if (ViewBag.SuccessMessage != null)
{
<div>
<label style="color: red;">#ViewBag.SuccessMessage</label>
</div>
}
</fieldset>
}
Here's the Model:
public class CreateSupport : SupportTicket
{
public CreateSupport()
{
ProductList = new List<Product>();
ProductVersionsList = new List<ProductVersion>();
EnviromentList = new List<InstallationEnvironment>();
content = new Content();
}
[Required]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Description { get; set; }
[Required]
[DisplayName("Browser version Info.")]
public string BrowserInfo { get; set; }
[Required]
[DisplayName("Database Version")]
public string DatabaseVersion { get; set; }
public Content content { get; set; }
}
The problem is that the values that reach the Controller are NULL even if you enter some value in them.
You should check your browser's developer tools to see if the form is properly posting its values. If it isn't, you should do two things:
A) Disabled javascript to see if there is a script that is interfering with the POST (typically either by disabling or clearing fields)
B) Ensuring your markup is valid using the W3C markup validation service
For input fields use
#Html.EditorFor(x => x.Subject)
For display fields use
#Html.DisplayFor(x => x.Subject)

EF database-first generated form won't validate

I've just created a new controller, along with its CRUD forms, etc, with a database-first EF model/entity.
Its throwing a number of validation errors on save, but since the form has validators, I don't see why this would be so.
For reasons that are beyond me, I'm not getting any validation to happen at all. It just goes right in to the saveChanges() call, which promptly fails.
Here's the edit form:
#model StatementsApplication.DAL.StatementTask
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>StatementTask</legend>
<div class="editor-label">
#Html.LabelFor(model => model.sInitials)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sInitials)
#Html.ValidationMessageFor(model => model.sInitials)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.dtCompleted)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.dtCompleted)
#Html.ValidationMessageFor(model => model.dtCompleted)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.sGroupLabel)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sGroupLabel)
#Html.ValidationMessageFor(model => model.sGroupLabel)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.nGroupSequence)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.nGroupSequence)
#Html.ValidationMessageFor(model => model.nGroupSequence)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.sTaskType)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sTaskType)
#Html.ValidationMessageFor(model => model.sTaskType)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.sTaskLabel)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.sTaskLabel)
#Html.ValidationMessageFor(model => model.sTaskLabel)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.nTaskSequence)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.nTaskSequence)
#Html.ValidationMessageFor(model => model.nTaskSequence)
</div>
#Html.HiddenFor(model => model.ID)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and here's the generated model:
namespace StatementsApplication.DAL
{
using System;
using System.Collections.Generic;
public partial class StatementTask
{
public int StmtBatchID { get; set; }
public string sInitials { get; set; }
public Nullable<System.DateTime> dtCompleted { get; set; }
public string sGroupLabel { get; set; }
public double nGroupSequence { get; set; }
public string sTaskType { get; set; }
public string sTaskLabel { get; set; }
public double nTaskSequence { get; set; }
public int ID { get; set; }
public virtual StatementBatch tblStmtBatch { get; set; }
}
}
and here's the controller bits...
//
// GET: /StatementTask/Edit/5
public ActionResult Edit(int id = 0)
{
StatementTask statementtask = db.StatementTasks.Find(id);
if (statementtask == null)
{
return HttpNotFound();
}
ViewBag.StmtBatchID = new SelectList(db.StatementBatches, "ID", "sStatus", statementtask.StmtBatchID);
return View(statementtask);
}
//
// POST: /StatementTask/Edit/5
[HttpPost]
public ActionResult Edit(StatementTask statementtask)
{
if (ModelState.IsValid)
{
try
{
db.Entry(statementtask).State = EntityState.Modified;
db.SaveChanges();
}
catch (Exception ex) {
throw ex;
}
return RedirectToAction("Index");
}
ViewBag.StmtBatchID = new SelectList(db.StatementBatches, "ID", "sStatus", statementtask.StmtBatchID);
return View(statementtask);
}
Its a matter of some confusion for me as to why sInitials is throwing 'required' validation errors, as well as why sGroupLabel is throwing length validation errors.
Thanks
a) your model has no data validation annotations. As such, MVC doesn't do any validation, because you're not telling it what to validate.
b) You don't mention what you are submitting. Are you just submitting an empty form?
it appears that Data Annotations will resolve this issue
[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public object Note { get; set; }
via http://fendy-huang.blogspot.com/2011/04/how-to-pass-empty-string-in-entity.html

MVC 3 dropdown list not getting any values

I have a dropdownlist in an MVC 3 create page, however I am not getting any values when I POST the page. My code is as follows :-
View :-
#using (Html.BeginForm("Create", "League", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
League
<div class="editor-label">
#Html.LabelFor(model => model.League.fk_CountryID, "Country")
</div>
<div class="editor-field">
#Html.DropDownList("fk_CountryID", "--Select One--") *
#Html.ValidationMessageFor(model => model.League.fk_CountryID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.League.LeagueName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.League.LeagueName)
#Html.ValidationMessageFor(model => model.League.LeagueName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.League.Image)
</div>
<div class="editor-field">
Upload File: <input type="file" name="Image" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Controller :-
[HttpPost]
public ActionResult Create([Bind(Exclude = "Image")]Country country, HttpPostedFileBase Image, League league)
{
if (ModelState.IsValid)
{
model.League = league;
try
{
foreach (string file in Request.Files)
{
HttpPostedFileBase fileUploaded = Request.Files[file];
if (fileUploaded.ContentLength > 0)
{
byte[] imageSize = new byte[fileUploaded.ContentLength];
fileUploaded.InputStream.Read(imageSize, 0, (int)fileUploaded.ContentLength);
model.League.Image = imageSize;
}
}
db.Leagues.AddObject(model.League);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception e)
{
ModelState.AddModelError("uploadError", e);
}
}
What am I doing wrong? Cannot get the dropdownlist value in the controller.
Thanks for your help and time
Ok fixed it by adding a SelectList in my ViewModel as follows :-
//Countries dropdown List
public SelectList CountryList { get; set; }
public string SelectedCountry { get; set; }
public LeagueData PopulateCountriesDDL(string selected, Country country)
{
var typeList = new SelectList(db.Countries.ToList(), "CountryID", "CountryName", selected);
LeagueData model = new LeagueData { CountryList = typeList, Country = country, SelectedCountry = selected };
return model;
}

Resources