I have a telerik asp.net mvc grid which needs to be populated based on the search criteria the user enters in separate text boxes. The grid is using ajax method to load itself initially as well as do paging.
How can one pass the search parameters to the grid so that it sends those parameters "every time" it calls the ajax method in response to the user clicking on another page to go to the data on that page?
I read the telerik's user guide but it does not mention this scenario. The only way I have been able to do above is by passing the parameters to the rebind() method on client side using jquery. The issue is that I am not sure if it is the "official" way of passing parameters which will always work even after updates.
I found this method on this post on telerik's site: link text
I have to pass in multiple parameters. The action method in the controller when called by the telerik grid runs the query again based on the search parameters.
Here is a snippet of my code:
$("#searchButton").click(function() {
var grid = $("#Invoices").data('tGrid');
var startSearchDate = $("#StartDatePicker-input").val();
var endSearchDate = $("#EndDatePicker-input").val();
grid.rebind({ startSearchDate: startSearchDate ,
endSearchDate: endSearchDate
});
});
So according to Telerik "recommended approach is to set the arguments in the onDataBinding event".
function onGridBinding(e) {
if (cancelGridBinding) {
// ...
}
else {
var searchValue = 'something';
e.data = { search: searchValue };
}
}
For myself I use ViewModel object that I pass using jQuery and javascript object, my View is stongly typed SearchMemberModel, witch contains my search fields and I have a Textbox for every fields in my view. My databinding is on passing the Model to the controller. Then I build my object in javascript and pass it to my controller in the rebind call.
Here's my code :
View and javascrip
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage<Enquete.Models.SearchMemberModel>" %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend><%: Resources.Search %></legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.MemberNumber) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.MemberNumber) %>
<%: Html.ValidationMessageFor(model => model.MemberNumber) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Email) %>
<%: Html.ValidationMessageFor(model => model.Email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.FirstName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FirstName) %>
<%: Html.ValidationMessageFor(model => model.FirstName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.LastName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.LastName) %>
<%: Html.ValidationMessageFor(model => model.LastName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Phone) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Phone) %>
<%: Html.ValidationMessageFor(model => model.Phone) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Active) %>
</div>
<div class="editor-field">
<%: Html.CheckBoxFor(model => model.Active) %>
<%: Html.ValidationMessageFor(model => model.Active) %>
</div>
<p>
<input type="submit" value="<%: Resources.ToSearch %>" id="btnSearch" />
</p>
</fieldset>
<% } %>
<%= Html.Telerik().Grid<SerializableMember>()
.Name("Grid")
.Columns(colums =>
{
colums.Bound(c => c.Email).Title(Resources.Email);//.ClientTemplate("<a href=\"" + Url.Action(MVC.Admin.Edit()) + "/<#=Id#>\" ><#=Email#></a>");
colums.Bound(c => c.FirstName).Title(Resources.FirstName);
colums.Bound(c => c.LastName).Title(Resources.LastName);
colums.Bound(c => c.MemberNumber).Title(Resources.MemberNumber);
colums.Bound(c => c.Active).Title(Resources.Active).HeaderHtmlAttributes(new { #class = "center-text" }).HtmlAttributes(new { #class = "center-text" }).ClientTemplate("<img src=\"Content/images/icons/<#=Active#>.png\" alt=\"<#=Active#>\" />");
colums.Bound(c => c.Id).Title(" ").HtmlAttributes(new { #class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.Member.ResetPassword()) + "/<#=Id#>\" title=\"" + Resources.ResetPassword + "\" >" + Resources.ResetPassword + "</a>");
colums.Bound(c => c.Id).Title(" ").HtmlAttributes(new { #class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.Member.Activate()) + "/<#=Id#>\" title=\"" + Resources.Activate + "\" >" + Resources.Activate + "</a>");
colums.Bound(c => c.Id).Title(" ").HtmlAttributes(new { #class = "center-text" }).ClientTemplate("<a href=\"" + Url.Action(MVC.Member.Deactivate()) + "/<#=Id#>\" title=\"" + Resources.Deactivate + "\" >" + Resources.Deactivate + "</a>");
})
//.DataBinding(d => d.Ajax().Select("ListAjax", "Member", Model))
.DataBinding(d => d.Ajax().Select(MVC.Member.ListAjax(Model).GetRouteValueDictionary()))
.Sortable()
.NoRecordsTemplate(Resources.NoData)
%>
<%= Html.AntiForgeryToken() %>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSearch').click(function () {
var grid = $('#Grid').data('tGrid');
var searchModel = {
MemberNumber: $('#MemberNumber').val(),
Email: $('#Email').val(),
FirstName: $('#FirstName').val(),
LastName: $('#LastName').val(),
Phone: $('#Phone').val(),
Active: $('#Active').is(':checked')
};
grid.rebind(searchModel);
return false;
});
});
</script>
<%= Html.Telerik().ScriptRegistrar().jQuery(false).DefaultGroup(g => g.DefaultPath("~/Content/Javascript/2010.3.1110"))%>
And that's my controller
[GridAction]
public virtual ActionResult ListAjax(SearchMemberModel search)
{
var gridModel = new GridModel<SerializableMember>();
var data = _session.All<Member>();
if (search != null)
{
if (search.Active) data = data.Where(x => x.Active);
if (!string.IsNullOrEmpty(search.Email)) data = data.Where(x => x.Email.Contains(search.Email));
if (!string.IsNullOrEmpty(search.FirstName)) data = data.Where(x => x.FirstName.Contains(search.FirstName));
if (!string.IsNullOrEmpty(search.LastName)) data = data.Where(x => x.LastName.Contains(search.LastName));
if (!string.IsNullOrEmpty(search.MemberNumber)) data = data.Where(x => x.MemberNumber.Contains(search.MemberNumber));
if (!string.IsNullOrEmpty(search.Phone)) data = data.Where(x => x.Phone.Contains(search.Phone));
}
var list = new List<SerializableMember>(data.Count());
list.AddRange(data.ToList().Select(obj => new SerializableMember(obj)));
gridModel.Data = list;
return View(gridModel);
}
I can give you my search model class too :
public class SearchMemberModel
{
[LocalizedDisplayName("MemberNumber")]
public string MemberNumber { get; set; }
[LocalizedDisplayName("Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[LocalizedDisplayName("FirstName")]
public string FirstName { get; set; }
[LocalizedDisplayName("LastName")]
public string LastName { get; set; }
[LocalizedDisplayName("Phone")]
public string Phone { get; set; }
[LocalizedDisplayName("ActiveOnly")]
public bool Active { get; set; }
}
Hope it can helps anyone out there!
This is actually documented here.
<script type="text/javascript">
$(document).ready(function () {
$('#apply').click(function () {
var params = {
showDisabled : $('input[name=ShowDisabled]').attr('checked'),
showExpired : $('input[name=ShowDisabled]').attr('checked')
};
var grid = $('#Grid').data('tGrid');
grid.rebind(params);
});
});
</script>
Here's the controller action bound to your select command:
[GridAction(EnableCustomBinding=true)]
public ActionResult _BindGrid(GridCommand command, string mode, int? id, bool showExpired, bool showDisabled)
{
return View(new GridModel(GetMessageGridItems(command, mode, id, showExpired, showDisabled)));
}
The param 'command' has the sorting and paging information. Note: this solution is for an ajax-ified grid. If you are doing straight-up posts, you can still use the GridCommand command parameter to maintain the state of paging/filtering/sorting.
Give this one a try: Telerik MVC Grid External Filter
It's a jquery plugin which enables you to set the filter by custom input controls.
Here is a much easier way to pass parameters back from your form during the telerix ajax post back.
Simply hook into the global $.ajaxPrefilter event and use jquery to serialize the contents of your from to the URL that is being submitted. This will work with ASP.MVC model binding
<script type="text/javascript">
$.ajaxPrefilter(function (options) {
options.url = options.url + "&" + $("form").serialize();
});
</script>
Related
Hi how are you? I'm trying to validate a form in ASP NET MVC.
I have a partial view "Address" that I reuse for some entities, like Company, Person, etc.
My problem is that when I submit the form, only the controls of the father view gets validated, the ones in the partial view don't.
Here's some code I hope u can geive me hand
PERSON VIEW
#model Entities.Person
#using (Html.BeginForm("Create", "Person", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.LabelFor(model => model.FirstName)
<div class="control">
#Html.TextBoxFor(model => model.FirstName, new { #maxlength = 7, #class = "numeric"})
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="spacer-short"></div>
</td>
<td>
#Html.LabelFor(model => model.LastName)
<div class="control">
#Html.TextBoxFor(model => model.LastName, new { #maxlength = 7, #class = "numeric"})
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="spacer-short"></div>
</td>
</tr>
</table>
#{ Html.RenderAction("Index", "Address", new {id = Model.AddressId});} //Renders the Address form part
<div class="spacer"></div>
<button type="submit" data-button="true" data-button-icon="ui-icon-disk" class="">Create</button>
<button type="button" data-button="true" data-button-icon="ui-icon-circle-close" class="button-cancel">Cancel</button>
}
ADDRESS VIEW
#model Entities.Address
<table>
<tr>
<td>
#Html.LabelFor(model => model.Street)
<div class="control">
#Html.TextBox("Address.Street", Model.Street)
#Html.ValidationMessage("Address.Street")
</div>
<div class="spacer-short"></div>
</td>
<td>
#Html.LabelFor(model => model.Number)
<div class="control">
#Html.TextBox("Address.Number", Model.Number)
#Html.ValidationMessage("Address.Number")
</div>
<div class="spacer-short"></div>
</td>
</tr>
</table>
Then I have some validation metadata ([Required]) for person and address fields
A common mistake using #Html.Partial(...) and expecting validation errors to show up is not passing ViewData to that partial.:
#Html.Partial([ViewName], [EmailAddressObject], ViewData)
Try this:
#Html.EditorFor(Model.Street)
#Html.ValidationMessageFor(Model.Street)
instead of this:
#Html.TextBox("Address.Street", Model.Street)
#Html.ValidationMessage("Address.Street")
Try using Html.Partial(...) instead of Html.RenderAction(...) to render the partial view. This may be suppressing the validations.
Model
İmportant: Manage Nuget Packages
=>> JQuery.Validation
=>> Microsoft.JQueryUnobtrusive.Validation
install.
1) First step
using System.ComponentModel.DataAnnotations;
2)
public int Id { get; set; }
[Required(ErrorMessage = "* Kategori adı boş geçilemez.")]
[DisplayName("Kategori Adı")]
public string CategoryName { get; set; }
[Required(ErrorMessage = "* Kategori açıklaması boş geçilemez.")]
[DisplayName("Kategori Açıklaması")]
public string Description { get; set; }
3)
if (model != null && ModelState.IsValid)
{
var categoryCreate = new Categories
{
//code
};
_CategoriesService.Create(categoryCreate);
}
4)
Add ViewModel
#model Models.CategoryViewModel
After
#Html.TextBoxFor(model => model.CategoryName, new { #class = "form-control input-sm", id = "categoryTitle", #placeholder = "Kategori adını giriniz.", #type= "text", #required=true })
#Html.ValidationMessageFor(model => model.CategoryName, "", new { #class = "error-message" })
#Html.TextBoxFor(model => model.Description, new { #class = "form-control input-sm", id = "categoryArticle", #placeholder = "Kategori açıklamasını giriniz.", #type = "text", #required = true })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "error-message" })
In my case, I was missing
<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>
Once I put that in my _layout.cshtml file, it started working even with partial views.
I have three model Classes(code first)
ProductGroup(p)->product(c)(list of produGroups comes in drop down list while creating a new product),
Now my requirement is,
Product(p)->PreferedLocation(c),
when I select preferedLocation(Create action) link ,I have to fill the details for the particular product.Means first I need to display single product name in Label like Product:Mango
In controller
public ActionResult PreferedLocation()
{
ViewBag.ProductID = new SelectList(db.Products,"ProductID","Name");
//ViewBag.CountryID = new SelectList(db.Countries, "CountryID", "Name");
return View();
}
//
// POST: /PreferedLocation/Create
[HttpPost]
public ActionResult PreferedLocation(PreferredLocation preferredlocation)
{
if (ModelState.IsValid)
{
db.PreferredLocations.Add(preferredlocation);
db.SaveChanges();
return RedirectToAction("Index");
}
// ViewBag.ProductID = new SelectList(db.Products, "ProductID", "Name", preferredlocation.ProductID);
return View(preferredlocation);
}
In View:
<div class="editor-field">
<%: Html.EditorFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.StreetAdress) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.StreetAdress) %>
<%: Html.ValidationMessageFor(model => model.StreetAdress) %>
</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.Latitude) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Latitude) %>
<%: Html.ValidationMessageFor(model => model.Latitude) %>
</div>
<div class="display-label">product</div>
<div class="display-field">
<%: Html.LabelFor(model=>Model.Product.Name) %>
<%: Html.ValidationMessageFor(model => model.ProductID) %>
</div>
Here I tried Code for idsplaying product name in label
but instead of product name I got output as
product
Product Name.
What modifications I have to do.
Use DisplayFor instead of LabelFor.
I try to make user registation form. I have two user types and want to make two JQuery UI tabs with forms. But tab is empty and in java script console error "GET http://localhost/ParcDocs/Admin/Users/AddWorker 500 (Internal Server Error)".
Code of user registration page:
<script type="text/javascript">
$(document).ready(function() {
$("#tabContainer").tabs();
});
</script>
<div id="tabContainer">
<ul>
<li>#Html.ActionLink("Пользователь", "AddUser", "Users", null, null)</li>
<li>#Html.ActionLink("Сотрудник", "AddWorker", "Users", null, null)</li>
</ul>
</div>
PartialView code:
#model ParcDocs.Models.WorkerUser
#using (Html.BeginForm("AddWorker", "Users"))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Пользователь</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.RoleId, ((IEnumerable<ParcDocs.Models.Role>)ViewBag.PossibleRoles).Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Name),
Value = option.Id.ToString(),
Selected = (Model != null) && (option.Id == Model.RoleId)
}), "Выберете роль пользователя")
</div>
<p>
<input type="submit" value="Добавить" />
</p>
</fieldset>
}
Controller code:
public ActionResult AddWorker()
{
var model = new WorkerUser();
return PartialView(model);
}
Same behavior this second tab.
You should be returning a PartialViewResult, rather than an ActionResult. Put a breakpoint on public ActionResult AddWorker() and see what exception you get. Paste it here so that we have more information.
This is my Controller:
/// <summary>
/// Activity
/// </summary>
/// <returns></returns>
public ActionResult CreateActivity()
{
AriaCRMEntities aria = new AriaCRMEntities();
var unit = from u in aria.ActivityGroupIDs select u;
List<SelectListItem> lst = new List<SelectListItem>();
foreach (var u in unit)
{
lst.Add(new SelectListItem { Text = u.ActivityGroupName.ToString(), Value = u.ActivityGroupID_FK.ToString() });
}
ViewData["activity"] = lst;
return View();
}
[HttpPost]
public ActionResult CreateActivity(FormCollection model)
{
if (ModelState.IsValid)
{
Activity activ = new Activity();
if (!string.IsNullOrEmpty(model["ActivityGroupID_FK"]))
{
AriaCRMEntities aria = new AriaCRMEntities();
activ.ActivityGroupID_FK = Int32.Parse(model["ActivityGroupID_FK"]);
activ.ActivityType = model["ActivityType"];
activ.ActivityDes = model["ActivityDes"];
aria.Activities.AddObject(activ);
aria.SaveChanges();
return RedirectToAction("Create");
}
}
return View(model);
}
This is my View :
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true,) %>
<fieldset>
<legend>Fields</legend>
<br />
<%:Html.DropDownListFor(model=>model.ActivityGroupID_FK , (IEnumerable<SelectListItem>)ViewData["activity"], "انتخاب نوع فعالیت")%><br />
<%Html.ValidationMessageFor (model=>model.ActivityGroupID_FK,"dddddddddd"); %>
<div class="editor-label">
<%: Html.LabelFor(model => model.ActivityType) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ActivityType) %>
<%: Html.ValidationMessageFor(model => model.ActivityType,"dfsaaa") %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.ActivityDes) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ActivityDes) %>
<%: Html.ValidationMessageFor(model => model.ActivityDes) %>
</div>
<p>
<input type="submit" value="Create" id="btn"/>
</p>
</fieldset>
<% } %>
But now I need to validate <%:Html.DropDownListFor%>. How do I create custom validation?
If you want to display a validation error message next to your drop-down list, you can do this from your controller like so:
ModelState.AddModelError("ActivityGroupID_FK", "The selected value is invalid.");
Update
I just noticed the validation message for your DropDownList looks like this:
<%Html.ValidationMessageFor (model=>model.ActivityGroupID_FK,"dddddddddd"); %>
You might want to change that like so:
<%: Html.ValidationMessageFor(model=>model.ActivityGroupID_FK,"dddddddddd") %>
Googling generally and on SO hasn't helped me yet, so:
I am building my first MVC application from scratch, going by the MVC Music Store example but instead building a little application where arena Fighters can be created and made to Fight each other. (Fighters and Fight have been made linked to underlying tables through EF).
I have controllers for both the Fighters and the Fights. The Edit Actionresult for Fights is working, but for Fighters it is not. When I hit the button to save my alterations I return to the associated Index page, but no changes have been committed. This is my question: why is this failing?
From BarracksController, with the faulty non-updating HttpPost Edit (should have been named FighterController, but neverthemind):
//
// GET: /Barracks/Edit
public ActionResult Edit(int id)
{
ViewData.Model = _FightDb.Fighters.Single(f => f.Id == id);
return View();
}
//
// POST: /Barracks/Edit
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var fighter = _FightDb.Fighters.Single(f => f.Id == id);
try
{
UpdateModel(fighter, "Fighter");
var x = ViewData.GetModelStateErrors();
_FightDb.SaveChanges();
return RedirectToAction("Index");
}
catch
{
var viewModel = fighter;
return View(viewModel);
}
}
(As you can see, I've included the GetModelStateErrors trick from this SO question, but the result for x is null)
This is the controller that does work, FightController:
//
// GET: /Fights/Edit
public ActionResult Edit(int id)
{
var viewModel = new FightDetailsViewModel
{
Fight = _FightDb.Fights.Single(f => f.ID == id),
Fighters = _FightDb.Fighters.ToList()
};
return View(viewModel);
}
//
// POST: /Fights/Edit
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var fight = _FightDb.Fights.Single(f => f.ID == id);
try
{
UpdateModel(fight, "Fight");
_FightDb.SaveChanges();
return RedirectToAction("Index");
}
catch
{
var viewModel = new FightDetailsViewModel
{
Fight = _FightDb.Fights.Single(f => f.ID == id),
Fighters = _FightDb.Fighters.ToList()
};
return View(viewModel);
}
}
This is edit.aspx for the Fighters: (Edited after comment)
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Mvc3_EF_BW_Fight.Models.Fighter>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphMain" runat="server">
<h2>Edit</h2>
<%: Html.EditorForModel() %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
</asp:Content>
Which uses the following Fighter.ascx in Shared:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Mvc3_EF_BW_Fight.Models.Fighter>" %>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fighter</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Id) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Id) %>
<%: Html.ValidationMessageFor(model => model.Id) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.FighterName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FighterName) %>
<%: Html.ValidationMessageFor(model => model.FighterName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.FighterStyleDescription) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FighterStyleDescription) %>
<%: Html.ValidationMessageFor(model => model.FighterStyleDescription) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.FighterLongDescription) %>
</div>
<div class="editor-field">
<%: Html.TextAreaFor(model => model.FighterLongDescription) %>
<%: Html.ValidationMessageFor(model => model.FighterLongDescription) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
This is the edit.aspx for Fights
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Mvc3_EF_BW_Fight.ViewModels.FightDetailsViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphMain" runat="server">
<h2>Edit</h2>
<%: Html.EditorFor(model => model.Fight, new { Fighters = Model.Fighters })%>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
</asp:Content>
And this is the Fight.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Mvc3_EF_BW_Fight.Models.Fight>" %>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.ID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.ID) %>
<%: Html.ValidationMessageFor(model => model.ID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.FightName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FightName) %>
<%: Html.ValidationMessageFor(model => model.FightName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Fighter1ID) %><br />
<%: Html.LabelFor(model => model.Fighter1Reference.Value.FighterName)%>
</div>
<div class="editor-field">
<%: Html.DropDownList("Fighter1ID", new SelectList(ViewData["Fighters"] as IEnumerable, "ID", "FighterName", Model.Fighter1ID))%>
<%: Html.ValidationMessageFor(model => model.Fighter1ID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Fighter2ID) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("Fighter1ID", new SelectList(ViewData["Fighters"] as IEnumerable, "ID", "FighterName", Model.Fighter1ID))%>
<%: Html.ValidationMessageFor(model => model.Fighter2ID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Fighter1Login) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Fighter1Login) %>
<%: Html.ValidationMessageFor(model => model.Fighter1Login) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Fighter2Login) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Fighter2Login) %>
<%: Html.ValidationMessageFor(model => model.Fighter2Login) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.FightStatusID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.FightStatusID) %>
<%: Html.ValidationMessageFor(model => model.FightStatusID) %>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
And this is my viewmodel for Fights:
public class FightDetailsViewModel
{
public Fight Fight { get; set; }
public List<Fighter> Fighters { get; set; }
}
There is no ViewModel for Fighters (none that is involved in this scenario, anyway).
I can post any code you may wish to see.
Edit: I've looked at Using ViewModel Pattern with MVC 2 Strongly Typed HTML Helpers and ASP.NET MVC 2 UpdateModel() is not updating values in memory or database , but i haven't seen a solution there yet.
Instead of this UpdateModel(fighter, "Fighter"); try calling the updte model just like this UpdateModel(fighter);. The difference is between the two edits that in case of Fighter your model is directly the Fighter so you do not need the name, while in case of the Fight you call the Editor for model.Fight so you need the name. See this question as well: asp.net mvc2 - how to get model and model.something in the same way in controller?