selected value in dropdownlist is not working - asp.net-mvc-3

I am trying to display a complex viewmodel in a view, everything works fine except one dropdownlist. I am displaying a list of enum, and set the selected object as it should be. But for an unknown reason, its not showing the selected value. I have tried many times with but failed -- please help me. The code is given below -
Enum:
public enum CommentStatus
{
NoStatus = 0,
Resolved = 1,
NotApplicable = 2
}
Model:
public class CheckComments
{
public string EntryId { get; set; }
public int Serial { get; set; }
public string Comment { get; set; }
public DateTime CommentDate { get; set; }
public CommentStatus CommentStatus { get; set; }
}
public class CheckDataViewModel
{
public string EntryId { get; set; }
public string CheckId { get; set; }
public decimal Value { get; set; }
public List<CheckComments> CheckCommentsList { get; set; }
public List<string> CommentStatusList { get; set; }
}
Controller:
public class CheckDataController : Controller
{
public ActionResult GetEnteredCheckData(string entryId)
{
var checkDataViewModel = new CheckDataViewModel();
var checkData = new CheckDataManager().GetCheckData(entryId);
checkDataViewModel.EntryId = checkData.EntryId;
checkDataViewModel.CheckId = checkData.CheckId;
checkDataViewModel.Value = checkData.Value;
checkDataViewModel.CheckCommentsList = checkData.Comments;
checkDataViewModel.CommentStatusList = Enum.GetNames(typeof (CommentStatus)).ToList();
return View("EnteredCheckData", checkDataViewModel);
}
}
View:
#model PDCA.Web.Models.CheckDataViewModel
#{
ViewBag.Title = "EnteredCheckData";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.EntryId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.EntryId)
#Html.HiddenFor(model => model.EntryId)
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Check Information</legend>
<div class="row">
<div class="span3">
<div class="text-left">#Html.LabelFor(model => model.CheckId)</div>
</div>
<div class="span3">
<div class="text-left">
#Html.DisplayFor(model => model.Check.CheckId)
#Html.HiddenFor(model => model.Check.CheckId)
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>Comments</legend>
<div>
<table class="table table-bordered">
<tr>
<th>
Serial
</th>
<th>
Comment
</th>
<th>
Date
</th>
<th>
Status
</th>
<th>
</th>
</tr>
#for (int i = 0; i < Model.CheckCommentsList.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Serial)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Serial)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].Comment)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].Comment)
</td>
<td>
#Html.DisplayFor(modelItem => Model.CheckCommentsList[i].CommentDate)
#Html.HiddenFor(modelItem => Model.CheckCommentsList[i].CommentDate)
</td>
<td>
#Html.DropDownListFor(modelItem => Model.CheckCommentsList[i].CommentStatus, new SelectList(Model.CommentStatusList, Model.CheckCommentsList[i].CommentStatus))
#Html.ValidationMessageFor(model => Model.CheckCommentsList[i].CommentStatus)
</td>
<td>
#Html.ActionLink("Update Status", "UpdateCommentStatus", new { Model.EntryId, Model.CheckCommentsList[i].Serial, Model.Check.CheckTitle, Model.Check.CheckId })|
#Html.ActionLink("Delete", "DeleteComment", new { Model.CheckCommentsList[i].Serial, Model.EntryId })
</td>
</tr>
}
</table>
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
The code is too lengthy but I think this will help you to understand my mistakes. Thanks in advance friends.

Solution:
#Html.DropDownListFor(modelItem => Model.CheckCommentsList[i].CommentStatus, new SelectList(Model.CommentStatusList, Model.CheckCommentsList[i].CommentStatus.ToString()))

Related

Partial View not showing data

I have a partial view which does not show the data. Here is a simple version. Here are my Models. The parent and child records
namespace Partial.Models
{
using System;
using System.Collections.Generic;
public partial class Parent
{
[System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Parent()
{
this.Children = new HashSet<Child>();
}
public int ID { get; set; }
public string Description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Child> Children { get; set; }
}
}
namespace Partial.Models
{
using System;
using System.Collections.Generic;
public partial class Child
{
public int ID { get; set; }
public Nullable<int> ParentID { get; set; }
public string Description { get; set; }
public virtual Parent Parent { get; set; }
}
}
Here are my controllers which only involve the index and edit forms.
namespace Partial.Controllers
{
public class ParentsController : Controller
{
private PartialEntities db = new PartialEntities();
// GET: Parents
public ActionResult Index()
{
return View(db.Parents.ToList());
}
namespace Partial.Controllers
{
public class ChildrenController : Controller
{
private PartialEntities db = new PartialEntities();
// GET: Children
public ActionResult Index()
{
var children = db.Children.Include(c => c.Parent);
return View(children.ToList());
}
Here is my view. Parent Form which is the edit form. Which should display the children index form
#model Partial.Models.Parent
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Parent</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<table class="table">
<tr>
<td>
Html.Partial("~/Views/Children/Index.cshtml", new List<Partial.Models.Child> ());
</td>
</tr>
</table>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Child Form which should display the children but doesn't
#model IEnumerable<Partial.Models.Child>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Parent.Description)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Parent.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
Please Try Code
Remove the code
Html.Partial("~/Views/Children/Index.cshtml", new List<Partial.Models.Child> ());
replace Code
#{Html.RenderAction("Index","Children");}
Sysntext For :
#Html.RenderAction("Action name","Controller name",Route values)

How to edit the bind data in GridView using asp.net MVC?

I have bind the data using grid in asp.net mvc3. I have a problem in edit link in the bind table. If I click on edit link it's not responding. Here's what I have:
Teacher.cs
public class Teacher
{
public static List<Teacher> GetList { get; set; }
public int T_Id { get; set; }
public string T_Name { get; set; }
public string T_Address { get; set; }
public string Sub_Id { get; set; }
}
Teachercontroller
public ActionResult Edit(int id,string T_Name,string T_Address,string Sub_Id)
{
// Teacher list= new Teacher();
var edit = EditList();
//list.T_Id = Convert.ToInt32(T_Id);
return View(edit);
}
[HttpPost]
public ActionResult EditList()
{
var editlist = new List<Teacher>();
using (SqlConnection conn = new SqlConnection(#"Integrated ecurity=SSPI;Persist Security Info=False;Initial Catalog=Demo;Data Source=CIPL41\SQLEXPRESS"))
{
conn.Open();
var modeledit = new Teacher();
SqlCommand cmd = new SqlCommand("edit", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#T_Id", modeledit.T_Id);
cmd.Parameters.AddWithValue("#T_Name", modeledit.T_Name);
cmd.Parameters.AddWithValue("#T_Address", modeledit.T_Address);
cmd.Parameters.AddWithValue("#Sub_Id", modeledit.Sub_Id);
cmd.ExecuteNonQuery();
conn.Close();enter code here
editlist.Add(modeledit);
}
return View(editlist);
}
This is My Html Code:
Index.cshtml:
#model IEnumerable<MvcApplication1.Models.Teacher>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
T_Id
</th>
<th>
T_Name
</th>
<th>
T_Address
</th>
<th>
Sub_Id
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.T_Id}) |
#Html.ActionLink("Details", "Details", new { id=item.T_Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.T_Id})
</td>
<td>
#item.T_Id
</td>
<td>
#item.T_Name
</td>
<td>
#item.T_Address
</td>
<td>
#item.Sub_Id
</td>
</tr>
}
**Edit.cshtml:**
#model MvcApplication1.Models.Teacher
#{
ViewBag.Title = "Edit";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Teacher</legend>
<div class="editor-label">
#Html.LabelFor(model => model.T_Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.T_Id)
#Html.ValidationMessageFor(model => model.T_Id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.T_Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.T_Name)
#Html.ValidationMessageFor(model => model.T_Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.T_Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.T_Address)
#Html.ValidationMessageFor(model => model.T_Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Sub_Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Sub_Id)
#Html.ValidationMessageFor(model => model.Sub_Id)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")

Required Validation Error Message is not getting displayed in jquery popup modal form

I have used ComponentModel.DataAnnotations [Required] attribute for validation messages. The message is not getting displayed in my form. However, the RegularExpression validation and Range validation are working fine.
In one of my field, I used both [Required] and [RegualarExpression]. When I give the wrong input in the text box, the RegualarExpression validation message appears and after erasing the input, then only Required validation message. Otherwise, Required validation message does not appear.
Here is my code:
--Model Class
public class Email
{
[Required(ErrorMessage = "Email Address is required!")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9] {1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "Invalid Email Address.")]
public virtual string EmailAddress { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "First Name is Required")]
public virtual string FirstName { get; set; }
public virtual string MiddleName { get; set; }
[Required(ErrorMessage = "Last Name is required!")]
public virtual string LastName { get; set; }
public virtual string Status { get; set; }
}
--View
#{Html.EnableClientValidation();}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("CreateEmail", "LeaderBoard", FormMethod.Post, new { enctype = "multipart/form-data", id = "create-email-dialog" }))
{
#Html.ValidationSummary(true)
{
<form>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="popTable">
<tr>
<td width="38%">
First Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Middle Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.MiddleName)
#Html.ValidationMessageFor(model => model.MiddleName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Last Name:
</td>
<td width="62%">
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</td>
</tr>
<tr>
<td width="38%">
Email Address:
</td>
<td width="62%">
<div class="errorMessage">
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
</td>
</tr>
<tr>
<td width="38%">
Status:
</td>
<td width="62%">
<div class="editor-field">
#Html.DropDownList("Status", ViewData["Status"] as SelectList)
</div>
</td>
</tr>
</table>
<input type="button" id="btnCreateEmail" value="Save" name="submit" class="btn" />
<input type="button" value="Cancel" name="cancel" class="closeDialog" />
</form>
}
}
--Controller
[HttpGet]
public ActionResult CreateEmail()
{
if (Request.IsAjaxRequest())
{
var list = new SelectList(new[]
{
new{Id = "Active", Name = "Active"},
new{Id = "Inactive", Name = "Inactive"}
},
"Id", "Name", 1);
ViewData["Status"] = list;
return PartialView("_CreateEmail");
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult CreateEmail(Email model)
{
using (_emailRepository)
{
if (ModelState.IsValid)
{
_emailRepository.Create(model);
return Json(new { success = true });
}
return RedirectToAction("Index");
}
}
Validate those fields in the document ready function
$( document ).ready( function ( e )
{
$( "form" ).validate().element( "#FirstName" );
$( "form" ).validate().element( "#LastName" );
});

MVC Model on Post has no navigation properties

I've looked around SO and I can't find anyone with an issue like this, so I'm posting this question.
I have a two edit actions in a controller (post and get) and in the GET I populate the Wine property of a viewmodel that gets passed to the view.
On the POST, I read that viewmodel, and save the changes to the database. After that I wanted to update my Lucene seach index with the updated Wine property. However, I keep getting an error because the Wine property doesn't have any of its navigation properties populated.
I tried looking up a new wine object using db.Wines.Find(ew.wine.WindID) but that still returns a Wine with no navigation properties. It is worth mentioning this is exactly what the GET edit action does, and the is populated correctly. I have no idea what is going on here. I also tried Wine w = db.Entry(ew.Wine).Entity to get those navigation properties populated, but to no avail... Thanks for the help in advance!
ViewModel & Wine Model
public class NewWineViewModel
{
public Wine Wine { get; set; }
public VOAVIRequest VOAVIRequest { get; set; }
public bool IsRequest { get; set; }
public SelectList VarTypes { get; set; }
public SelectList Origins { get; set; }
public SelectList Apps { get; set; }
public SelectList Vintages { get; set; }
public SelectList Importers { get; set; }
public NewWineViewModel()
{
this.Wine = new Wine();
}
}
public class Wine :Updater
{
public int WineID { get; set; }
//public int WineTypeID { get; set; }
[Display(Name = "Varietal/Type")]
public int? VarTypeID { get; set; }
[Display(Name = "Origin")]
public int? OriginID { get; set; }
[Display(Name = "Appellation")]
public int? AppID { get; set; }
[Display(Name = "Vintage")]
public int? VintageID { get; set; }
[Display(Name = "Importer")]
public int? ImporterID { get; set; }
public int ProducerID { get; set; }
public string Designate { get; set; }
[Display(Name = "Drink Window")]
public string DrinkWindow { get; set; }
public string Body { get; set; }
public string SKU { get; set; }
[Display(Name = "Varietal Makeup")]
public string VarietalMakeup { get; set; }
[Display(Name = "Case Production")]
public string CaseProduction { get; set; }
[Display(Name = "Alcohol Content")]
public double? AlcoholContent { get; set; }
public string Winemaker { get; set; }
[Display(Name = "Consulting Winemaker")]
public string ConsultWinemaker { get; set; }
public bool Sustainable { get; set; }
public bool Kosher { get; set; }
public bool Organic { get; set; }
public bool Biodynamic { get; set; }
public bool SalmonSafe { get; set; }
public Boolean Active { get; set; }
[Display(Name = "ResidualSugar")]
public double? RS { get; set; }
public double? pH { get; set; }
public string QRUrl { get; set; }
public virtual WineType WineType { get; set; }
public virtual VarType VarType { get; set; }
public virtual Origin Origin { get; set; }
public virtual App App { get; set; }
public virtual Vintage Vintage { get; set; }
public virtual Importer Importer { get; set; }
public virtual Producer Producer { get; set; }
}
Two Edit Actions from the controller:
[ProducerEdit]
public ActionResult Edit(int WineID)
{
NewWineViewModel ew = new NewWineViewModel();
ew.Wine = db.Wines.Find(WineID);
ew.VarTypes = new SelectList(db.VarTypes, "VarTypeID", "Name", ew.Wine.VarTypeID);
ew.Origins = new SelectList(db.Origins, "OriginID", "Name", ew.Wine.OriginID);
ew.Apps = new SelectList(db.Apps, "AppID", "Name", ew.Wine.AppID);
ew.Vintages = new SelectList(db.Vintages, "VintageID", "Name", ew.Wine.VintageID);
//might need to handle null on this one
ew.Importers = new SelectList(db.Importers, "ImporterID", "Name", ew.Wine.ImporterID);
return View(ew);
}
//post
[HttpPost]
[ProducerEdit]
public ActionResult Edit(NewWineViewModel ew)
{
if (ModelState.IsValid)
{
ew.Wine.Body = ew.Wine.Body == "Please select wine body" ? string.Empty : ew.Wine.Body;
ew.Wine.UpdatedBy = User.Identity.Name;
ew.Wine.UpdatedOn = DateTime.Now;
db.Entry(ew.Wine).State = EntityState.Modified;
db.SaveChanges();
Wine w = db.Wines.Find(ew.Wine.WineID);
Lucene.LuceneSearch.ClearLuceneIndexRecord(ew.Wine.WineID);
Lucene.LuceneSearch.AddUpdateLuceneIndex(ew.Wine);
if (ew.IsRequest)
{
ew.VOAVIRequest.WineID = ew.Wine.WineID;
ew.VOAVIRequest.CreatedBy = User.Identity.Name;
ew.VOAVIRequest.CreatedOn = DateTime.Now;
db.VOAVIRequests.Add(ew.VOAVIRequest);
db.SaveChanges();
return RedirectToAction("Requested");
//redirect to "Request Submitted" page for new wines
}
return RedirectToAction("Details", new { id = ew.Wine.WineID });
}
else
{
ew.VarTypes = new SelectList(db.VarTypes, "VarTypeID", "Name", ew.Wine.VarTypeID);
ew.Origins = new SelectList(db.Origins, "OriginID", "Name", ew.Wine.OriginID);
ew.Apps = new SelectList(db.Apps, "AppID", "Name", ew.Wine.AppID);
ew.Vintages = new SelectList(db.Vintages, "VintageID", "Name", ew.Wine.VintageID);
//might need to handle null on this one
ew.Importers = new SelectList(db.Importers, "ImporterID", "Name", ew.Wine.ImporterID);
return View(ew);
}
}
EDIT - here is the form in Razor
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<h3>#ViewBag.ProducerName</h3>
#Html.HiddenFor(m => m.Wine.WineID)
#Html.HiddenFor(m => m.Wine.ProducerID)
#Html.HiddenFor(m => m.IsRequest)
<h4 style="margin-top: -40px; padding-bottom: 10px;">Editing #Model.Wine.Name</h4>
<table>
<tr>
<td>#Html.LabelFor(m => m.Wine.VarTypeID)
</td>
<td style="display: inline">
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.VarTypeID, Model.VarTypes, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.VarType, new { style = "display: none;", #class = "voavignore" })
<a id="lnkNewVar" class="filetypes" href="#">New Varietal?</a> #* #Html.ValidationMessageFor(m => m.VOAVIRequest.VarType)*#
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.OriginID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.OriginID, Model.Origins, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.Origin, new { style = "display: none;", #class = "voavignore" })
<a id="lnkNewOrigin" class="filetypes" href="#">New Origin?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.AppID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.AppID, Model.Apps, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.App, new { style = "display: none;", #class = "voavignore" })<a
id="lnkNewApp" class="filetypes" href="#">New Varietal?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.VintageID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.VintageID, Model.Vintages, new { #class = "chzn-select" })
</div>
#Html.TextBoxFor(m => m.VOAVIRequest.Vintage, new { style = "display: none;", #class = "voavignore" })
<a id="lnkNewVintage" class="filetypes" href="#">New Varietal?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Designate)
</td>
<td>
#Html.EditorFor(m => m.Wine.Designate)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.DrinkWindow)
</td>
<td>
#Html.EditorFor(m => m.Wine.DrinkWindow)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.VarietalMakeup)
</td>
<td>
#Html.EditorFor(m => m.Wine.VarietalMakeup)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Body)
</td>
<td>
#Html.DropDownListFor(m => m.Wine.Body, new SelectList(Model.Wine.BodyList, "Text", "Text", Model.Wine.Body), new { #class = "chzn-select" })
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.ImporterID)
</td>
<td>
<div class="voavi-select">
#Html.DropDownListFor(m => m.Wine.ImporterID, Model.Importers, new { #class = "chzn-select" })</div>
#Html.TextBoxFor(m => m.VOAVIRequest.Importer, new { style = "display: none;" })
<a id="lnkNewImporter" class="filetypes" href="#">New Varietal?</a>
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.SKU)
</td>
<td>
#Html.EditorFor(m => m.Wine.SKU)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.CaseProduction)
</td>
<td>
#Html.EditorFor(m => m.Wine.CaseProduction)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.AlcoholContent)
</td>
<td>
#Html.EditorFor(m => m.Wine.AlcoholContent)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.RS)
</td>
<td>
#Html.EditorFor(m => m.Wine.RS)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.pH)
</td>
<td>
#Html.EditorFor(m => m.Wine.pH)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Winemaker)
</td>
<td>
#Html.EditorFor(m => m.Wine.Winemaker)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.ConsultWinemaker)
</td>
<td>
#Html.EditorFor(m => m.Wine.ConsultWinemaker)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Sustainable)
</td>
<td>
#Html.EditorFor(m => m.Wine.Sustainable)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Kosher)
</td>
<td>
#Html.EditorFor(m => m.Wine.Kosher)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Organic)
</td>
<td>
#Html.EditorFor(m => m.Wine.Organic)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.Biodynamic)
</td>
<td>
#Html.EditorFor(m => m.Wine.Biodynamic)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(m => m.Wine.SalmonSafe)
</td>
<td>
#Html.EditorFor(m => m.Wine.SalmonSafe)
</td>
</tr>
</table>
<p>
<input type="submit" value="Update" />
</p>
}

both create and list in the same view MVC3

so what Iam trying to do is a view wiht both create and list in the same view, so I've read that I can usea ViewModel for this so I create my view model "EventoViewModel"
public class EventoViewModel
{
public Eventos Eventos { get; set; }
public IEnumerable<Eventos> LEventos { get; set; }
}
my controller:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Eventos eventos)
{
if (ModelState.IsValid)
{
db.Eventos.AddObject(eventos);
db.SaveChanges();
}
return RedirectToAction("Create");
}
My view: in the foreach part I get an ERROR, say nullreferenceException, what Iam doing wrong?
#model createList.Models.EventoViewModel
<h2>Create</h2>
#using (Html.BeginForm()) {
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Eventos.Nombre)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Eventos.Nombre)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<table>
<tr>
<th>
Nombre
</th>
</tr>
#foreach (var item in Model.LEventos) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nombre)
</td>
</tr>
}
</table>
I change my approach I use partial view now. and create a "List" partial view
Partial View: List
#model IEnumerable<createList.Models.Eventos>
<table>
<tr>
<th>
Nombre
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nombre)
</td>
</tr>
}
</table>
and in the end of my "create" view I call my "List" Partial view
#model createList.Models.Eventos
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Eventos</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Nombre)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Nombre)
#Html.ValidationMessageFor(model => model.Nombre)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
**#{Html.RenderAction("list", "Evento");}** // call de action "list"
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and my controllers:
public ViewResult List()
{
return View(db.Eventos.ToList()); //past a list of eventos
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Eventos eventos)
{
if (ModelState.IsValid)
{
db.Eventos.AddObject(eventos);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(eventos);
}

Resources