when i will select check box and will be clicked select button how i can get this value to the textbox value. Here checkbox id= chk and textbox id = OrderNo. Please help me ....I have something in below....
$("#OrderNo").blur(function() {
$.get('/Ordering/OrderList/', function(data) {
$('#orlist').html(data);
});
$('#orlist').dialog({
width: 500,
height: 350,
open: true,
title: 'Select Order',
buttons: {
Select: function() {
if (("#chk") == 'checked') {
var por = ("#porderno").val();
por = ("#OrderNo");
}
},
Cancel: function() {
$('#orlist').dialog('close');
$('#orlist').empty();
}
}
});
Partial view page is
#model IEnumerable<testcon.OrderM>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.OdrId)
</th>
<th>
#Html.DisplayNameFor(model => model.OrderNo)
</th>
<th>
#Html.DisplayNameFor(model => model.CId)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.CheckBox("OdrId", new { #id="chk"})
</td>
<td class="left">
#Html.DisplayFor(modelItem => item.OrderNo, new { #id="porderno"})
</td>
<td class="left">
#Html.DisplayFor(modelItem => item.CId)
</td>
</tr>
}
</table>
And My Create View page is
#model testcon.DeliveryInfo
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>DeliveryInfo</legend>
#*<div class="editor-label">
#Html.LabelFor(model => model.DId)
</div>*#
<div class="editor-field">
Delivery Id : #Html.EditorFor(model => model.DId)
#Html.ValidationMessageFor(model => model.DId)
</div>
#*<div class="editor-label">
#Html.LabelFor(model => model.OrderNo)
</div>*#
<div class="editor-field">
Order No :#Html.EditorFor(model => model.OrderNo)
#Html.ValidationMessageFor(model => model.OrderNo)
#*Show Order*#
</div>
#* <div class="editor-label">
#Html.LabelFor(model => model.DDate)
</div>*#
<div class="editor-field">
Delivery Date : #Html.EditorFor(model => model.DDate)
#Html.ValidationMessageFor(model => model.DDate)
</div>
#*<div class="editor-label">
#Html.LabelFor(model => model.DQuantity)
</div>*#
<div class="editor-field">
Delivery Quantity: #Html.EditorFor(model => model.DQuantity)
#Html.ValidationMessageFor(model => model.DQuantity)
</div>
#*<div class="editor-label">
#Html.LabelFor(model => model.DAmount)
</div>*#
<div class="editor-field">
Delivery Amount : #Html.EditorFor(model => model.DAmount)
#Html.ValidationMessageFor(model => model.DAmount)
</div>
<div id="orlist" >
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Use .is(':checked') check if checked...
buttons: {
Select: function() {
if ($("#chk").is(':checked')) {
$("#OrderNo").val($("#porderno").val());
}
},
to check if the check box is checked in jQuery, you can do it by either
//will return true if the check box is checked otherwise false!
$("#chkBoxId").is(':checked');
or
this approach is good when dealing with group of radio buttons/checkboxes.
//will yield the same result if checkbox is checked
$('input[name="chkBoxName"]:checked').val();
So you can use them in your code like what #Anthony Chu has responded which i was about to write :)
Related
I have a scenario where in I need to store multiple rows in a single table.Let me explain it in detail.
I have a table Price which has 4 columns, ID, ModelID, AppSettingID,Amount.
I am looking for inserting multiple values to the table where
ID would be the Primary Key.
ModelID would be same for all the rows.
AppSettingID and Amount will be different for all the rows and would be based on the selection user does on the view.
I have bound the AppSettingID to different combo boxes on the view as I have it categorized in the database.
This is what I am doing right now.
View:
<div class="editor-label">
#Html.LabelFor(model => model.ModelID, "Model")
</div>
<div class="editor-field">
#Html.DropDownList("ModelID", String.Empty)
#Html.ValidationMessageFor(model => model.ModelID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AppsettingID, "Mobile Condition")
</div>
<div class="editor-field">
#Html.DropDownList("Mobile Condition", new SelectList(ViewBag.ConditionID, "Text", "Value"))
#Html.ValidationMessageFor(model => model.AppsettingID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Amount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => model.Amount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AppsettingID, "Tennure")
</div>
<div class="editor-field">
#Html.DropDownList("Tennure", new SelectList(ViewBag.AppsettingID, "TexT", "Value"))
#Html.ValidationMessageFor(model => model.AppsettingID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Amount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => model.Amount)
</div>
<p>
<input type="submit" value="Create" />
</p>
Controller:
public ActionResult Create()
{
//ViewBag.AppsettingID = db.Appsettings.Select(r => r.ID).Distinct();
ViewBag.ModelID = new SelectList(db.Models, "ID", "Name");
//ViewBag.Tennure = db.Appsettings.Select(s => s.Type == "Tennure").Distinct();
IQueryable<Appsetting>TennureIDs = db.Appsettings.Where(s => s.Type == "Tennure").Distinct();
IQueryable<Appsetting> Conditions = db.Appsettings.Where(s => s.Type == "Mobile Condition").Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in TennureIDs)
{
SelectListItem s = new SelectListItem();
s.Text = t.ID.ToString();
s.Value = t.Value.ToString();
items.Add(s);
}
ViewBag.AppsettingID = items;
List<SelectListItem> conds = new List<SelectListItem>();
foreach (var t in Conditions)
{
SelectListItem s = new SelectListItem();
s.Text = t.ID.ToString();
s.Value = t.Value.ToString();
conds.Add(s);
}
ViewBag.ConditionID = conds;
return View();
}
//
// POST: /Price/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Price price, FormCollection form)
{
if (ModelState.IsValid)
{
int test = Convert.ToInt16(form["Mobile Condition"]);
price.AppsettingID = test;
db.Prices.Add(price);
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.AppsettingID = new SelectList(db.Appsettings, "ID", "Type", price.AppsettingID);
//ViewBag.ModelID = new SelectList(db.Models, "ID", "Name", price.ModelID);
return View(price);
}
I hope this solution will help you
The following is a razor page, here I have displayed the model in table format
#model List<MyModel>
<h2>Create</h2>
#using (Html.BeginForm())
{
<table>
<tr>
<th>
Model ID
</th>
<th>
App Setting ID
</th>
<th>
Amount
</th>
</tr>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.TextBoxFor(x => Model[i].ModelID)
</td>
<td>
#Html.TextBoxFor(x => Model[i].AppsettingID)
</td>
<td>
#Html.TextBoxFor(x => Model[i].Amount)
</td>
</tr>
}
</table>
<input type="submit" />
}
When user clicks the submit button, it will pass the model to the controller
Controller
[HttpPost]
public ActionResult Create(List<MyModel> m)
{
// Do Coding
return View("Create", m);
}
I have a model named "Professional" that have as attribute a list of other objects named "Skill".
At my edit page I'm trying to do something that will list all skills persisted at database and the user will choice someone and create a link with that skill.
But I have no idea how can i achieve this:
My Edit View:
#model TCCApplication.Models.ProfessionalModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ProfessionalModel</legend>
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.UserAccount.Id)
#Html.HiddenFor(model => model.UserAddress.Id)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.BirthDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BirthDate)
#Html.ValidationMessageFor(model => model.BirthDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Profession)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Profession)
#Html.ValidationMessageFor(model => model.Profession)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserAccount.Username)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserAccount.Username)
#Html.ValidationMessageFor(model => model.UserAccount.Username)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserAccount.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserAccount.Password)
#Html.ValidationMessageFor(model => model.UserAccount.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserAddress.Street)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserAddress.Street)
#Html.ValidationMessageFor(model => model.UserAddress.Street)
</div>
<fieldset class="row">
<legend>Habilidades</legend>
#foreach (var skill in Model.Skills)
{
#Html.HiddenFor(sk => skill.Id)
<div class="col-md-10">
<div class="display-label">
#Html.Label("Nome da habilidade: ")
#Html.DisplayFor(sk => skill.Name)
</div>
<div class="display-label">
#Html.Label("Descrição")
#Html.DisplayFor(sk => skill.Description)
</div>
<div class="display-label">
#Html.Label("Categoria: ")
#Html.DisplayFor(sk => skill.Category.Name)
</div>
</div>
<div class="col-md-2">
#Html.ActionLink("Deletar Skill", "DeleteSkill", new { skillId = skill.Id, professionalId = Model.Id })
</div>
}
<p>
<div>
#Html.DropDownList("Skills", (IEnumerable<SelectListItem>)ViewBag.skills)
</div>
</p>
<div>
#Html.ActionLink("Adicionar habilidade não presente na lista", "AddNewSkill", new { professionalId = Model.Id})
</div>
</fieldset>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
This will get a list of distinct strings from the database.
Controller:
ViewBag.Skills = db.Skills.OrderBy(c=>c.Name).Select(c => c.Name).Distinct().ToList();
This will put the strings gathered previously into a multi-select list.
View:
#Html.DropDownListFor(model => model.Skills, ((List<int>)ViewBag.Skills).Select(m=> new SelectListItem{Value = m.ToString(CultureInfo.InvariantCulture), Text = m.ToString(CultureInfo.InvariantCulture)}), new {multiple = "multiple"})
You can approach this a bit more intelligently by creating a list of SelectListItems from the result of your db result by putting the value to the ID and the text to the name. That'll make it easier to save changes later.
I am getting this error when trying to load a partial view, and I don't know what the issue is:
System.InvalidOperationException: The model item passed into the
dictionary is of type 'CDB.OrderM', but this dictionary requires a
model item of type
'System.Collections.Generic.IEnumerable`1[CDB.tblItem]'.
public ActionResult Index()
{
OrderM om = new OrderM();
List<tblItem> tList = db.Query<tblItem>("Select * from tblItem").ToList<tblItem>();
ViewBag.tList = tList;
return View(om);
}
public ActionResult Reqitem()
{
//tblItem ti= db.Query<tblItem>("select * from tblItem");
var ti = db.Query<tblItem>("select * from tblItem");
return PartialView("_rawmat",ti);
}
My Partial View codes are-
#model IEnumerable<CDB.tblItem>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.ItemId)
</th>
<th>
#Html.DisplayNameFor(model => model.ItemName)
</th>
<th>
#Html.DisplayNameFor(model => model.MeasuringUnit)
</th>
<th>
#Html.DisplayNameFor(model => model.Rate)
</th>
<th>
#Html.DisplayNameFor(model => model.Quantity)
</th>
<th>
#Html.DisplayNameFor(model => model.BagSz)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ItemId)
</td>
<td>
#Html.DisplayFor(modelItem => item.ItemName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MeasuringUnit)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.BagSz)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
and Index view codes are...
#model CDB.OrderM
#{
ViewBag.Title = "Index";
var tList = ViewBag.tList;
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>OrderM</legend>
<div class="editor-label">
#Html.LabelFor(model => model.OdrId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrId)
#Html.ValidationMessageFor(model => model.OdrId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OrderNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OrderNo)
#Html.ValidationMessageFor(model => model.OrderNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OdrDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrDate)
#Html.ValidationMessageFor(model => model.OdrDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OdrQty)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrQty)
#Html.ValidationMessageFor(model => model.OdrQty)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OdrAmount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OdrAmount)
#Html.ValidationMessageFor(model => model.OdrAmount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DDate)
#Html.ValidationMessageFor(model => model.DDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CId)
#Html.ValidationMessageFor(model => model.CId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Pod)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Pod)
#Html.ValidationMessageFor(model => model.Pod)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
#Html.Partial("_rawmat")
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
It looks like what you want to do is change #Html.Partial("_rawmat") to #Html.Action("Reqitem"). This is because your original statement says go straight to the view and since you haven't passed a model it will pass the same model as the view that it is included on.
So if you use #Html.Partial("_rawmat") on your index view it will pass the model that it has which is of type OrderM and not actually call the action you have written at all.
I dont know why you people are missing out the available syntax to call a partial view with a model
{#Html.RenderPartial("_PartialView",List<CDB.tblItem>) }
Where I assume the partial view uses the Model of type List<CDB.tblItem>.
If you want to populate the model with any values. just before the above syntax use
#{
//code to populate your model
}
If your partial view is expecting a List, then change the method like this...
public ActionResult Reqitem()
{
//tblItem ti= db.Query<tblItem>("select * from tblItem");
var ti = db.Query<tblItem>("select * from tblItem").ToList();//notice to List
return PartialView("_rawmat",ti);
}
I have added .ToList() to the end of the query.
I think the issue is in the second call of #Html.Partial("_rawmat") inside your Index.
It does not pass a model parameter, so it passed the default one, which is a CDB.OrderM.
Use this instead (it renders the action instead of the partial view):
#Html.Action("Reqitem")
I have form which contains some text filed for filling data. I want to fill data in text box after dropdownlist changed.
MyView.chstml
#model BloodBank.Models.NewCamp
#{
ViewBag.Title = "New Camp";
Layout = "~/Views/Shared/_Layout - Menu.cshtml";
}
<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>
<script type="text/javascript">
$(function () {
$("select#OrganisationID").change(function (evt) {
if ($("select#OrganisationID").val() != "0") {
$.ajax({
url: "GetOrganizationInfo?orgID=" + $("select#OrganisationID").val(),
type: 'POST',
data: { OS: $("select#OrganisationID").val() },
success: function (response) {
$("select#OrganisationID").replaceWith(response)
},
error: function (xhr) {
alert("Something went wrong, please try again");
}
});
}
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "New Camp creation was unsuccessful. Please correct the errors and try again.")
<div>
<table style="border-style:none;border-width:0;border:0;">
<tbody>
<tr>
<td style="border:0;vertical-align:middle;">
<div class="editor-label">
#Html.LabelFor(m => m.OrganisationID)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.DropDownListFor(m => m.OrganisationID, (SelectList)ViewBag.OrganisationList)
#* <select id="Area">
#foreach (var arearow in (SelectList)ViewBag.OrganisationList)
{
<option value="#arearow.Value">#arearow.Text</option>
}
</select>*#
#Html.ActionLink("Add New Organisation", "AddOrganisation", "Organisation", null, null)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.ValidationMessageFor(m => m.OrganisationID)
</div>
</td>
</tr>
<tr>
<td style="border:0;text-align:left;" colspan="2"> <h3>Contact Person Information</h3></td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.Email)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.FirstName)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.LastName)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.Phone)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.Phone)
#Html.ValidationMessageFor(m => m.Phone)
</div>
</td>
</tr>
<tr>
<td colspan="2" style="border:0;text-align:center;">
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" id="ClickMe" class="cssLoginButton blue"/>
</div>
}
My Action
[Authorize]
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult NewCamp()
{
var user = (BloodBank.Security.BloodBankMembershipUser)Membership.GetUser();
this.BindOrganisations(user.BloodBankID);
return View();
}
public ActionResult GetOrganizationInfo(string orgID)
{
if (!string.IsNullOrEmpty(orgID))
{
var model = (new UserManager()).GetCampPersonOrganisationDetailsByOrganisationID(orgID);
Models.NewCamp newcampModel = new Models.NewCamp();
if (model.Count > 0)
{
newcampModel.CampID = model[0].CampID;
newcampModel.Organisation = "";
newcampModel.OrganisationID = model[0].OrganisationID;
newcampModel.FirstName = model[0].FirstName;
newcampModel.LastName = model[0].LastName;
newcampModel.Email = model[0].Email;
newcampModel.Phone = model[0].Phone;
var organisations = this.GetOrganisations(model[0].BloodBankID);
if (organisations != null)
ViewBag.OrganisationList = new SelectList(organisations, "OrganisationID", "NameCity");
}
return View("NewCamp", newcampModel);
}
else
return View();
}
I am not able to fill data in the form. I am not getting why I am not able to fill data. Is there any change in script or in my code? Is there any example to fill data after dropdownlist value changed?
--------- Update------------
I have tried similar thing on a sample project. Here I can fetch the values and display in text box, but I get one more view added on same View every time I choose OS from dropdown as in below screenshot.
the only flaw in the code you posted might be a missing ;
success: function (response) {
$("select#OrganisationID").replaceWith(response);
},
Hello Everyone I have solved my problem using this. There is no need to create any javascript. I have solved this without using javascript.
#Html.DropDownListFor(m => m.OrganisationID, (SelectList)ViewBag.OrganisationList, new { onchange = "document.location.href = 'NewCamp?orgID=' + this.options[this.selectedIndex].value;" })
I have a Create cshtml Page as follows :-
#model MvcCommons.ViewModels.CompositeViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</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>Article</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.ArticleTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ArticleViewModel.Article.ArticleTitle)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.ArticleTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.ArticleDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ArticleViewModel.Article.ArticleDate)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.ArticleDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.ArticleText)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ArticleViewModel.Article.ArticleText)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.ArticleText)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.ArticleSource)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ArticleViewModel.Article.ArticleSource)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.ArticleSource)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.CategoryID, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryID", String.Empty)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.CategoryID)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and then I am getting the viewModel inside the Create Action as follows :-
[HttpPost]
public ActionResult Create(CompositeViewModel viewModel)
{
if (ModelState.IsValid)
{
unitOfWork.ArticleRepository.Insert(viewModel.ArticleViewModel.Article);
unitOfWork.Save();
return RedirectToAction("Index");
}
PopulateDropDownList(viewModel.ArticleViewModel.Article.CategoryID);
return View(viewModel);
}
The PopulateDropDownList code is as follows :-
private void PopulateDropDownList(object selectedCategory = null)
{
var categoryQuery = unitOfWork.CategoryRepository.Get(
orderBy: q => q.OrderBy(d => d.CategoryTitle));
ViewBag.CategoryID = new SelectList(unitOfWork.CategoryRepository.Get(), "CategoryID", "CategoryTitle", selectedCategory);
}
My problem is that the CategoryID inside the CompositeViewModel viewModel is always 0 no matter what values I choose in the dropdown list! The other data entered in the Create cshtml is filled correctly inside the viewModel.
I cannot spot what I am doing wrong.
Thanks for your help and time
Shouldn't you be using DropDownListFor:
#Html.DropDownListFor(model => model.ArticleViewModel.Article.CategoryID, (SelectList)ViewBag.CategoryID)
You should write
#Html.DropDownList("ArticleViewModel.Article.CategoryID", ViewBag.CategoryID, null)
so ModelBinding works correctly or even use DropDownListFor<>().