Linq formating DateTime to dd-MM-yyyy in SELECT - linq

I need formartar to select the date in "dd-MM-yyyy", but I'm not getting. Have tested in various ways, but none work. Field formating is: DtFabricacao. I'm using DataTable and want to format the date in Linq prórpio
The Linq is below:
public static ResultadoListagemPadrao Grid(string orderna, string ordenaTipo, string filtro, int filtroID = 0)
{
ERPContext db = new ERPContext();
var resultado = new ResultadoListagemPadrao();
var dados = db.ProdutoLote.ToListERP();
var where = "";
var id = 0;
resultado.TotalRegistros = dados.Count();
resultado.Dados =
(from a in dados.AsQueryable()
select new
{
a.ProdutoLoteID,
a.Lote,
a.Identificacao,
a.DtFabricacao,
a.DtValidade,
a.QtdeAtual,
a.QtdeEmUtilizacao
})
.Where(where, filtro)
.OrderBy(orderna + " " + ordenaTipo);
return resultado;
}
Model:
public class ProdutoLote : IEntidadeBase
{
[Key]
public int ProdutoLoteID { get; set; }
public int ProdutoID { get; set; }
public string Lote { get; set; }
public string Identificacao { get; set; }
public string Detalhe { get; set; }
public DateTime? DtFabricacao { get; set; }
public DateTime? DtValidade { get; set; }
public decimal QtdeAtual { get; set; }
public decimal QtdeEmUtilizacao { get; set; }
public int EmpresaID { get; set; }
public string Fixo { get; set; }
public string Status { get; set; }
public string Apagado { get; set; }
public DateTime? DtApagado { get; set; }
public int UsuCad { get; set; }
public DateTime DtCad { get; set; }
public int UsuAlt { get; set; }
public DateTime DtAlt { get; set; }
public int UsuUltAlt { get; set; }
public DateTime DtUltAlt { get; set; }
[ForeignKey("UsuCad")]
public virtual Usuario UsuarioCad { get; set; }
[ForeignKey("UsuAlt")]
public virtual Usuario UsuarioAlt { get; set; }
[ForeignKey("UsuUltAlt")]
public virtual Usuario UsuarioUltAlt { get; set; }
[ForeignKey("EmpresaID")]
public virtual Empresa Empresa { get; set; }
[ForeignKey("ProdutoID")]
public virtual Produto Produto { get; set; }
}
View
#model ERP.Models.Produto
#{
ViewBag.Title = Html.MontaTitulo("Detalhe produto - " + #Model.ProdutoID.ToString());
}
<script type="text/javascript">
var oTableSetor;
$(document).ready(function () {
GridProdutoLote();
});
function GridProdutoLote() {
if (oTableSetor===undefined)
{
oTableGrid = $('#lista_lote').dataTable({
"bServerSide": true,
"sAjaxSource": '#Html.Raw(#Url.Action("ListaGenerica", "Home", new { aController = "ProdutoLote", filtroID = #Model.ProdutoID } ))',
"bProcessing": true,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "mDataProp": "ProdutoLoteID", "sTitle": "ID"},
{ "mDataProp": "Lote", "sTitle": "Lote" },
{ "mDataProp": "Identificacao", "sTitle": "Identificacao"},
{ "mDataProp": "DtFabricacao", "sTitle": "DtFabricacao"},
{ "mDataProp": "DtValidade", "sTitle": "DtValidade"},
{ "mDataProp": "QtdeAtual", "sTitle": "QtdeAtual"},
{ "mDataProp": "QtdeEmUtilizacao", "sTitle": "QtdeEmUtilizacao"},
{ "mData": null, "bSortable": false, "fnRender": function (o) {return '<a class="icone_16x16_detalhe" href=/Setor/Detalhar/' + o.aData["ProdutoLoteID"] + '>D</a>';}}
],
});
$('#lista_lote_filter input').unbind();
$("#lista_lote").show();
$("#grid_lote").show();
$('#lista_lote_filter input').bind('keyup', function(e) {
if(e.keyCode == 13) {
oTableGrid.fnFilter(this.value);
}});
}
};
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
#Html.HiddenFor(m => m.ProdutoID)
#Html.HiddenFor(m => m.ProdutoBase.Identificacao)
#Html.HiddenFor(m => m.ProdutoBase.Descricao)
<div class="linha left">
#Html.LabelFor(m => m.Identificacao) #Html.ValidationMessageFor(m => m.Identificacao)<br />
#Html.TextBoxFor(m => m.Identificacao, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.Descricao) #Html.ValidationMessageFor(m => m.Descricao)<br />
#Html.TextBoxFor(m => m.Descricao, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.Detalhe) #Html.ValidationMessageFor(m => m.Detalhe)<br />
#Html.TextBoxFor(m => m.Detalhe, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.ProdutoBase.UnidadeMedidaID) * #Html.ValidationMessageFor(m => m.ProdutoBase.UnidadeMedidaID)<br />
#Html.DropDownList("ProdutoBase.UnidadeMedidaID", (SelectList)ViewBag.ListaUnidadeMedida, String.Empty, new { style = "width:250px;" }) #Html.ValidationMessageFor(m => m.ProdutoBase.UnidadeMedidaID)<br />
#Html.LabelFor(m => m.ProdutoBase.Fracao) * #Html.ValidationMessageFor(m => m.ProdutoBase.Fracao)<br />
#Html.TextBoxFor(m => m.ProdutoBase.Fracao, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.ProdutoBase.QtdeFracao) * #Html.ValidationMessageFor(m => m.ProdutoBase.QtdeFracao)<br />
#Html.TextBoxFor(m => m.ProdutoBase.QtdeFracao, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.ProdutoBase.UnidadeMedidaIDFracao) * #Html.ValidationMessageFor(m => m.ProdutoBase.UnidadeMedidaIDFracao)<br />
#Html.DropDownList("ProdutoBase.UnidadeMedidaIDFracao", (SelectList)ViewBag.ListaUnidadeMedidaFracao, String.Empty, new { style = "width:250px;" }) #Html.ValidationMessageFor(m => m.ProdutoBase.UnidadeMedidaIDFracao)<br />
#Html.LabelFor(m => m.QtdeMinima) #Html.ValidationMessageFor(m => m.QtdeMinima)<br />
#Html.TextBoxFor(m => m.QtdeMinima, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.QtdeIdeal) #Html.ValidationMessageFor(m => m.QtdeIdeal)<br />
#Html.TextBoxFor(m => m.QtdeIdeal, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.QtdeMaxima) #Html.ValidationMessageFor(m => m.QtdeMaxima)<br />
#Html.TextBoxFor(m => m.QtdeMaxima, new { style = "width:250px;" })<br />
#Html.LabelFor(m => m.QtdeAtual) #Html.ValidationMessageFor(m => m.QtdeAtual)<br />
#Html.TextBoxFor(m => m.QtdeAtual, new { style = "width:250px;", #readonly = "readonly" })<br /><br />
#Html.CheckBoxFor(m => m.ProdutoBase.TemLoteBool, new { #class = "input normal" }) #Html.LabelFor(m => m.ProdutoBase.TemLoteBool) #Html.ValidationMessageFor(m => m.ProdutoBase.TemLoteBool)<br />
#Html.CheckBoxFor(m => m.ProdutoBase.FracionadoBool, new { #class = "input normal" }) #Html.LabelFor(m => m.ProdutoBase.FracionadoBool) #Html.ValidationMessageFor(m => m.ProdutoBase.FracionadoBool)<br />
<br />
Campos marcados com *, são do produto base e somente podem ser visualizados e não alterados
<br /><br />
#Html.MontaBotoesTelaDetalhar()
<br /><br />
</div>
}
<div class="linha left" id="grid_lote">
<div class="linha left separadora" >Dados de lote:</div>
<br />
<br />
<table id="lista_lote" class="display">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br /><br />
<br /><br />

Error 2 Cannot convert lambda expression to type 'string' because it is not a delegate type . This is happening because you have done this .OrderBy(orderna + " " + ordenaTipo); in Grid method, try instead the below code which also formats date
EDIT:
var queryResult = dados.AsQueryable().Where(where, filtro)
.OrderBy(dado => dado.ColumnName1)
.ThenBy(dado => dado.ColumnName2).ToList();
resultado.Dados =
(from a in queryResult
select new
{
a.ProdutoLoteID,
a.Lote,
a.Identificacao,
a.DtFabricacao.HasValue() ? a.DtFabricacao.Value.ToString("dd-MM-yyyy") : a.DtFabricacao,
a.DtValidade,
a.QtdeAtual,
a.QtdeEmUtilizacao
});

Related

How to bind dropdown list from action method in MVC 3 inside create view

I want to populate a dropdownlist on create view with form also. Here is my code
#model CM.Models.TVSerialEpisode
#{
ViewBag.Title = "AddEpisode";
}
#Html.Action("ListAllSeason","TvSerial") //here i want to call this action method so i could bind all tv serial
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>TVSerialEpisode</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Serial_ID)
</div>
<div class="editor-field">
#Html.DropDownList("Serial_ID", new List<SelectListItem>
{
new SelectListItem { Text = "Backstrom", Value="16" },
new SelectListItem{Text="10 Things I hate about You", Value="15"},
new SelectListItem { Text = "Castle", Value="14" }
}, "Select Serial")
#Html.ValidationMessageFor(model => model.Serial_ID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Episode_No)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Episode_No)
#Html.ValidationMessageFor(model => model.Episode_No)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Episode_Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Episode_Name)
#Html.ValidationMessageFor(model => model.Episode_Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.File_Url_480p)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.File_Url_480p)
#Html.ValidationMessageFor(model => model.File_Url_480p)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.File_Url_720p)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.File_Url_720p)
#Html.ValidationMessageFor(model => model.File_Url_720p)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Is_Active)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Is_Active)
#Html.ValidationMessageFor(model => model.Is_Active)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
here is the model class
namespace CM.Models
{
[Table("tbltvserial")]
public class TVSerial
{
[Key]
public Int64 Serial_ID { get; set; }
public string Serial_Name { get; set; }
public string Season_Name { get; set; }
public int Season_No { get; set; }
public int? Release_Year { get; set; }
}
public class TVSerial_VM
{
public Int64 Serial_ID { get; set; }
public string Serial_Name { get; set; }
public int Season_No { get; set; }
}
[Table("tblserialepisode")]
public class TVSerialEpisode
{
[Key]
public Int64 Video_ID { get; set; }
public Int64 Serial_ID { get; set; }
public int Episode_No { get; set; }
public string Episode_Name { get; set; }
public string File_Url_480p { get; set; }
public string File_Url_720p { get; set; }
public string Description { get; set; }
public bool Is_Active { get; set; }
public DateTime Uploaded_Time { get; set; }
}
public class TvSerialContext : DbContext
{
public DbSet<TVSerialEpisode> TvSerialEpisodes { get; set; }
public DbSet<TVSerial> TvSerials { get; set; }
}
}
here are controller class
public class TvSerialController : Controller
{
public List<TVSerial_VM> ListAllSeason()
{
try
{
TvSerialContext tvContext = new TvSerialContext();
List<TVSerial_VM> tv = tvContext.TvSerials
.Select(t => new TVSerial_VM
{
Serial_Name = t.Serial_Name,
Season_No=t.Season_No,
Serial_ID=t.Serial_ID
}).OrderBy(t=> t.Season_Name).
ToList();
return (tv);
}
catch (Exception ex)
{
return null;
}
}
}
public class TvSerialEpisodeController : Controller
{
TvSerialContext tvContext = new TvSerialContext();
public ActionResult AddEpisode()
{
return View();
}
[HttpPost]
public ActionResult AddEpisode(TVSerialEpisode tvEpisode)
{
if (ModelState.IsValid)
{
tvContext.TvSerialEpisodes.Add(tvEpisode);
tvContext.SaveChanges();
return RedirectToAction("AddEpisode");
}
return View(tvEpisode);
}
}
I don't know how to bind the tvserial list inside above view page. basically i want to choose the serial id from dropdown list, is this posible to call a action method inside the create view.
To populate your SelectList from the database, in the controllers AddEpisode() method use
ViewBag.SerialList = db.TvSerials.ToList().Select(x => new SelectListItem(){ Value = x.Serial_ID.ToString(), Text = x.Serial_Name });
and then in the view use
#Html.DropDownListFor(m => m.Serial_ID, (IEnumerable<SelectListItem>)ViewBag.SerialList, "Select Serial")
although it is recommended you use a view model and include a IEnumerable<SelectListItem> SerialList property in the view model so that it is
#Html.DropDownListFor(m => m.Serial_ID, Model.SerialList, "Select Serial")

MVC3 Why is my posted model NULL?

Curious issue with MVC3, EF Code First.
I'm passing a model that wraps two models to a view.
public class UserInfoModel
{
[Key]
[Required]
public int Id { get; set; }
/// <summary>
/// <para>Corresponds to ProviderUserKey in ASP Membership</para>
/// <para>Used in Membership.GetUser(ProviderUserKey) to retrieve email and username.</para>
/// </summary>
public Guid MembershipId { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Last name")]
public string LastName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Address 1")]
public string Address1 { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Address 2")]
public string Address2 { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "State")]
public string State { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Country")]
public string Country { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Zip code")]
public string ZipCode { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Sign up date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:MM/dd\/yyyy}")]
public DateTime SignUpDate { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Birthday")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:MM\/dd\/yyyy}")]
public DateTime BirthDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Enrollment date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:MM\/dd\/yyyy}")]
public DateTime EnrollmentDate { get; set; }
[DataType(DataType.ImageUrl)]
[Display(Name = "Avatar")]
public string AvatarImage { get; set; }
[Display(Name = "Rank")]
public int RankId { get; set; }
[ForeignKey("RankId")]
public UserRankModel Rank { get; set; }
[Display(Name = "IsActive")]
public bool IsActive { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class UserInfoAndRegisterModel
{
public UserInfoModel UserInfoModel { get; set; }
public RegisterModel RegisterModel { get; set; }
}
View:
#model K2Calendar.Models.UserInfoAndRegisterModel
#{
ViewBag.Title = "Update User";
}
<div class="container">
<h2>
Update Account Details</h2>
<p>
Use the form below to update the account.
</p>
<p>
#Html.ValidationSummary(true, "Account update was unsuccessful. Please correct the errors and try again.")
</p>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.UserInfoModel.Id)
#Html.HiddenFor(m => m.UserInfoModel.MembershipId)
#Html.HiddenFor(m => m.UserInfoModel.SignUpDate)
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.RegisterModel.UserName)
#Html.TextBoxFor(m => m.RegisterModel.UserName, new { tabindex = "1" , disabled = "disabled" } )
#Html.ValidationMessageFor(m => m.RegisterModel.UserName)
</div>
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.State)
#Html.TextBoxFor(m => m.UserInfoModel.State, new { tabindex = "8" })
#Html.ValidationMessageFor(m => m.UserInfoModel.State)
</div>
</div>
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.RegisterModel.Email)
#Html.TextBoxFor(m => m.RegisterModel.Email, new { tabindex = "2" , disabled = "disabled" })
#Html.ValidationMessageFor(m => m.RegisterModel.Email)
</div>
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.ZipCode)
#Html.TextBoxFor(m => m.UserInfoModel.ZipCode, new { tabindex = "9" })
#Html.ValidationMessageFor(m => m.UserInfoModel.ZipCode)
</div>
</div>
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.FirstName)
#Html.TextBoxFor(m => m.UserInfoModel.FirstName, new { tabindex = "3" })
#Html.ValidationMessageFor(m => m.UserInfoModel.FirstName)
</div>
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.Country)
#Html.TextBoxFor(m => m.UserInfoModel.Country, new { tabindex = "10" })
#Html.ValidationMessageFor(m => m.UserInfoModel.Country)
</div>
</div>
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.LastName)
#Html.TextBoxFor(m => m.UserInfoModel.LastName, new { tabindex = "4" })
#Html.ValidationMessageFor(m => m.UserInfoModel.LastName)
</div>
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.BirthDate)
#Html.TextBoxFor(m => m.UserInfoModel.BirthDate, new { tabindex = "11", placeholder = "mm/dd/yyyy" })
#Html.ValidationMessageFor(m => m.UserInfoModel.BirthDate)
</div>
</div>
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.Address1)
#Html.TextBoxFor(m => m.UserInfoModel.Address1, new { tabindex = "5" })
#Html.ValidationMessageFor(m => m.UserInfoModel.Address1)
</div>
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.EnrollmentDate)
#Html.TextBoxFor(m => m.UserInfoModel.EnrollmentDate, new { tabindex = "12", placeholder = "mm/dd/yyyy" })
#Html.ValidationMessageFor(m => m.UserInfoModel.EnrollmentDate)
</div>
</div>
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.Address2)
#Html.TextBoxFor(m => m.UserInfoModel.Address2, new { tabindex = "6" })
#Html.ValidationMessageFor(m => m.UserInfoModel.Address2)
</div>
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.RankId)
#Html.DropDownListFor(m => m.UserInfoModel.RankId, (SelectList)ViewBag.RankList, new { tabindex = "13" })
</div>
</div>
<div class="row-fluid">
<div class="span6">
#Html.LabelFor(m => m.UserInfoModel.PhoneNumber)
#Html.TextBoxFor(m => m.UserInfoModel.PhoneNumber, new { tabindex = "7" })
#Html.ValidationMessageFor(m => m.UserInfoModel.PhoneNumber)
</div>
<div class="span6">
</div>
</div>
<br />
<p>
<button type="submit" class="btn btn-primary btn-large" tabindex = "14">Update »</button>
</p>
}
My controller classes takes the model that is posted and does some db updates.
One of the wrapped models is null:
[Authorize]
[HttpPost]
public ActionResult Edit(UserInfoAndRegisterModel model)
{
//WHY IS model.RegisterModel == null ??//
if (ModelState.IsValid)
{
try
{
dbContext.Entry(model.UserInfoModel).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();
return RedirectToAction("Index", "Home");
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to update UserInfoModel", ex.InnerException);
}
}
GenerateRanksList();
return View(model);
}
I do the same thing for the account creation and I do not receive a null value for RegisterModel with almost identical view code.
Currently this is a non-issue in that I only update the UserInfoModel currently but in the future I may want to allow a user to change their email address or user name.
Any ideas?
Your RegisterModel is null because you are not posting any values which belongs to the RegisterModel
Although you have inputs which belong to RegisterModel like this in your view
#Html.TextBoxFor(m => m.RegisterModel.UserName,
new { tabindex = "1" , disabled = "disabled" } )
They are all disabled and disabled inputs are not posted:
Form submission - Successful controls
A successful control is "valid" for submission
However:
Controls that are disabled cannot be successful.
So you need remove the disable or add the properties as hidden fields:
#Html.HiddenFor(m => m.RegisterModel.UserName)

View to Controller in mvc3

I have a problem on passing values from view to controller
Here is my view:
#model IEnumerable<SQLOperation.Models.QuestionClass.Tabelfields>
#{
ViewBag.Title = "Question";
}
<h3> Question</h3>
#{int i = 0;}
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "Home"))
{
#Html.DisplayFor(modelItem => item.QuestionName)
#Html.HiddenFor(m => item.QuestionID)
<br /><br />
if (item.Option1 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option1, item)
#Html.DisplayFor(modelItem => item.Option1)
<br /><br />
}
if (item.Option2 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option2, item)
#Html.DisplayFor(modelItem => item.Option2)
<br /><br />
}
if (item.Option3 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option3, item)
#Html.DisplayFor(modelItem => item.Option3)
<br /><br />
}
if (item.Option4 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option4, item)
#Html.DisplayFor(modelItem => item.Option4)
<br /><br />
}
i = (Int16)i + 1;
if (Model.Count() == i)
{
<input name="btnsumbit" type="submit" value="Submit Feedback"
style="font-family:Segoe UI Light;font-size:medium;"/>
}
}
}
My controller :
[HttpGet]
public ActionResult Question(string email)
{
var tf = new QuestionClass.Tabelfields();
IList<QuestionClass.Tabelfields> viewmodel = new List<QuestionClass.Tabelfields>();
var q = QuestionClass.getallQuestion(email).ToList();
foreach (SQLOperation.Models.Question item in q)
{
QuestionClass.Tabelfields viewItem = new QuestionClass.Tabelfields();
viewItem.Email = item.Email;
viewItem.QuestionID = item.QuestionID;
viewItem.QuestionName = item.QuestionName;
viewItem.Option1 = item.Option1;
viewItem.Option2 = item.Option2;
viewItem.Option3 = item.Option3;
viewItem.Option4 = item.Option4;
viewmodel.Add(viewItem);
}
return View(viewmodel);
}
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
My Model:
public class QuestionClass
{
public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
public class Tabelfields : Question
{
//public decimal QuestionID { get; set; }
//public string Email { get; set; }
//public string QuestionName { get; set; }
//public string Option1 { get; set; }
//public string Option2 { get; set; }
//public string Option3 { get; set; }
//public string Option4 { get; set; }
public string SelectedOption { get; set; }
}
public static List<Question> getallQuestion(string email)
{
var list = (from q in context.Questions where q.Email == #email select q);
return list.ToList();
}
}
however I get NULL in "items" in controller.
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
Whereas if I change my View & Controller to below , I get last value from database in controller
View:
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "home", new { email=item.Email, q=item.QuestionID}))
{
#Html.DisplayFor(modelItem => item.QuestionName)
#Html.HiddenFor(m => item.QuestionID)
.
.
.
.
}
}
Controller:
[HttpPost, ActionName("Question")]
public void Question(string email,int q)
{
}
I get values in email and q
so how can I get all values i.e. QuestionId,Email,Questionname and it's appropriate selected value (radiobutton) in controller ?
i.e. in Following Controller:
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
You need to index the Html.*For items as such;
#Html.RadioButtonFor(m => m[i].SelectedOption, item.Option3, item)
To make things simplier, i'd probably get rid of the foreach & and separate i declaration and use the following;
#for(int i=0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].QuestionID)
#Html.RadioButtonFor(m => m[i].SelectedOption, Model[i].Option3, Model[i])
}
etc.
Indexing like this will cause the html to be rendered with the indexing intact:
<input type='hidden' name=[0].'QuestionId' />
<input type='hidden' name=[1].'QuestionId' />
<input type='hidden' name=[2].'QuestionId' />
Rather than what you're doing currently, which ends up rendering as so;
<input type='hidden' name='QuestionId' />
<input type='hidden' name='QuestionId' />
<input type='hidden' name='QuestionId' />
Without the indexing, each form field is given the same name, so you're controller is going to think only one was returned.

Checkboxes in editor template are not bound to model in post action

I am using an editor template to display a checkbox for each role a user can be assigned to. The model is:
public class UserModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public IEnumerable<string> UserRoles { get; set; }
}
public class UserRoleModel
{
public IEnumerable<RoleViewModel> AllRoles { get; set; }
public UserModel user { get; set; }
public UserRoleModel()
{
this.AllRoles = Roles.GetAllRoles().Select(r => new RoleViewModel
{
Name = r
});
this.user = new UserModel();
}
}
public class RoleViewModel
{
public string Name { get; set; }
public bool Selected { get; set; }
}
The Controller:
public ActionResult Create()
{
return View(new UserRoleModel());
}
[HttpPost]
public ActionResult Create(UserRoleModel model)
{
if (ModelState.IsValid)
{
MembershipCreateStatus createStatus;
Membership.CreateUser(model.user.UserName, model.user.Password, model.user.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
foreach (var r in model.AllRoles)
{
if (r.Selected)
{
Roles.AddUserToRole(model.user.UserName, r.Name);
}
}
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
return View(model);
}
The view:
#model BBmvc.Areas.Tools.Models.UserRoleModel
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>UserModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.user.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.user.UserName)
#Html.ValidationMessageFor(model => model.user.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.user.Email)
#Html.ValidationMessageFor(model => model.user.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.user.Password)
#Html.ValidationMessageFor(model => model.user.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user.ConfirmPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.user.ConfirmPassword)
#Html.ValidationMessageFor(model => model.user.ConfirmPassword)
</div>
<div class="editor-field">
#Html.EditorFor(x => x.AllRoles)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
and the editor template
#model BBmvc.Areas.Tools.Models.RoleViewModel
#Html.CheckBoxFor(x => x.Selected)
#Html.LabelFor(x => x.Selected, Model.Name)
#Html.HiddenFor(x => x.Name)
<br />
The problem is that no distinction is made in the post action whether any checkbox is checked or not. It seems that it is not getting bound to the model somehow.
Your issue comes from the deferred execution of LINQ queries. You need to eagerly initialize the collection:
public class UserRoleModel
{
public IEnumerable<RoleViewModel> AllRoles { get; set; }
public UserModel user { get; set; }
public UserRoleModel()
{
this.AllRoles = Roles.GetAllRoles().Select(r => new RoleViewModel
{
Name = r
}).ToList();
this.user = new UserModel();
}
}
Notice the .ToList() call:
this.AllRoles = Roles.GetAllRoles().Select(r => new RoleViewModel
{
Name = r
}).ToList();
And here's the explanation. When you write:
this.AllRoles = Roles.GetAllRoles().Select(r => new RoleViewModel
{
Name = r
});
at this moment the query is not executed. Only an expression tree is built but the actual query is executed only when something starts iterating over the collection. And what starts iterating? First it's the view. Inside the view you use an editor template for this collection:
#Html.EditorFor(x => x.AllRoles)
Since AllRoles is a collection property ASP.NET MVC will automatically iterate and render the editor template for each element of the collection. So this works to properly render the view.
Now let's see what happens when the form is POSTed. You post to the Create action and the default model binder kicks in. The constructor is called but since there is nothing to iterate over the AllRoles property this time the query is not executed. In fact it is executed later inside the action and the values are lost.
For this reason I would recommend you to avoid initializing your view models inside constructors. It would be better to do this inside the respective controller actions:
public class UserRoleModel
{
public IEnumerable<RoleViewModel> AllRoles { get; set; }
public UserModel user { get; set; }
}
and then:
public ActionResult Create()
{
var model = new UserRoleModel
{
AllRoles = Roles.GetAllRoles().Select(r => new RoleViewModel
{
Name = r
}).ToList(),
user = new UserModel()
};
return View(model);
}

jQuery and ASP.NEt MVC validation: Prevent validation on server

I have model that looks like this:
public class Lesson
{
public int Id { get; set; }
[Required(ErrorMessage = "Naam voor de les is verplicht")]
[Display(Name="Naam")]
public string Name { get; set; }
[Required(ErrorMessage = "Tijd is verplicht")]
[Display(Name="Tijd")]
public string Time { get; set; }
//Prijs is default exclusief BTW
[Required(ErrorMessage = "Prijs is verplicht")]
[Display(Name="Prijs (excl btw)")]
public double Price { get; set; }
[Display(Name = "Maximum aantal leerlingen")]
public int MaxStudents { get; set; }
}
And a create view that looks like this:
<div>
<div>
#Html.LabelFor(model => model.Name)
</div>
<div>
#Html.TextBoxFor(model => model.Name, new { #class = "gt-form-text" })
#Html.ValidationMessageFor(model => model.Name)
</div>
<div>
#Html.LabelFor(model => model.Time)
</div>
<div>
#Html.TextBoxFor(model => model.Time, new { #class = "gt-form-text" })
#Html.ValidationMessageFor(model => model.Time)
</div>
<div>
#Html.LabelFor(model => model.Price)
</div>
<div>
#Html.TextBoxFor(model => model.Price, new { #class = "gt-form-text" })
#Html.ValidationMessageFor(model => model.Price)
</div>
<div>
#Html.LabelFor(model => model.MaxStudents)
</div>
<div>
#Html.TextBoxFor(model => model.MaxStudents,
new { #class = "gt-form-text" })
#Html.ValidationMessageFor(model => model.MaxStudents)
</div>
</div>
In the Application_Start() method I set DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes to false.
MaxStudents is nullable and not required, nevertheless, if MaxStudents is null, the Modelstate is not valid (ModelState.IsValid = false).
My errormessage is not shown, instead of that I get the errormessage is A value is required.
What can I do to get ModelState.IsValid to be true?
Someone shared this with me, and I'll pass it on in case it helps. Sometimes those validation errors get swallowed up and are hard to find. When I was having a similar issue, I added this code to my ActionResult (HttpPost) and it got me right to the error in question.
try
{
db.Entry(myModel).State = EntityState.Modified;
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
} // }

Resources