So i get values for my drop down list but i wanted to get selected value from this dropdown. How to do this ?
Model:
public partial class Region
{
public int Id_regionu { get; set; }
public string Nazwa { get; set; }
}
Controller:
public class HomeController : Controller
{
private inzS9776Entities db = new inzS9776Entities();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
public ActionResult Index()
{
ViewBag.Regiony = new SelectList(db.Region,"Id_regionu", "Nazwa");
return View();
}
and View with dropdown:
<div class="jumbotron">
<legend>
<h2>Wyszukaj wycieczkÄ™</h2></legend><br/>
<form action="">
<div class="container">
Wybierz kierunek:
#Html.DropDownList("Regiony",null, String.Empty)<br />
Data wyjazdu:
<input class="date" type="date" name="startDate"><br><br>
</div>
</form>
`
Replace your <form action=""> to:
#using (Html.BeginForm("MyActionName") {
// ...
//here add to your dropdown and give it a name
#Html.DropDownList("Regiony", null, String.Empty)
// ...
}
The name attribute of your <select> element (dropdown list) will be "Regiony".
In your controller:
public ActionResult MyActionName(string Regiony) {
// here Regiony variable contains the selected value.
// ...
}
Here is an approach which I take;
1) Retreive the items and store it in a list of SelectListItem.
2) Use the list of SelectListItem to assign it to a drop down list.
3) Use the model field to bind the drop down list with the selected value
View
<div class="col-sm-8">
#{
List<SelectListItem> listItems = new List<SelectListItem>();
foreach (LookupData l in Model.HeatingTypeData)
{
listItems.Add(new SelectListItem { Text = l.LookupDescription, Value = l.LookupCode });
}
}
#Html.DropDownListFor(m => m.HeatingType, listItems, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.HeatingType)
</div>
Models:
The model (VoidProperty) used in the example contains the HeatingType as a List of LookupData and a method to get the list:
public List<LookupData> HeatingTypeData { get; set; }
public static List<LookupData> GetHeatingType()
{
return LookupData.GetDataList("HeatingType").OrderBy(m => m.SortOrder).ToList();
}
and then the LookupData:
public class LookupData : ILookup
{
public string LookupCode { get; set; }
public string LookupDescription { get; set; }
public int SortOrder { get; set; }
public static List<LookupData> GetDataList(string LookupGroup)
{
DBContexts.VoidsDBContext context = new DBContexts.VoidsDBContext();
var Params = new SqlParameter { ParameterName = "LookupGroup", Value = LookupGroup };
return context.Database.SqlQuery<LookupData>("p_LookupList #LookupGroup", Params).ToList();
}
}
The controller returns the view and pass an instance of the model;
VoidProperty _property = new VoidProperty();
......
......
_property.HeatingTypeData = VoidProperty.GetHeatingType();
......
return View(_property);
Related
I created a form to store information about the customers and his membership type. For that I am using the drop down list to hold values for membership types. But on submitting the form, the value(Id) for membership type isnt added to database
//Model Membership Types
public int Id { get; set; }
public string Name { get; set; }
//ViewModel NewCustomerviewModel
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
public Customers Customers{ get; set; }
//Controler CustomerController
public IActionResult Index()
{
var customers = _context.Customers.Include(c => c.MembershipTypes).ToList();
return View(customers);
}
[HttpPost]// Create is the aciton for Submit Button
public IActionResult Create(Customers customers)
{
_context.Customers.Add(customers);
_context.SaveChanges();
return RedirectToAction("Index", "Customers");
}
//View Model
#model Wes.ViewModels.NewCustomerviewModel;
#Html.DropDownListFor(m => m.Customers.MembershipTypes, new SelectList(Model.MembershipTypes, "Id", "Name"),"Select Membership Type", new { #class = "form-control" })
When the Form is Submitted, it should add all the values to the database including the value of Drop Down List Membership Types
You could try doing it this way:
//model
public int Id { get; set; }
public string Name { get; set; }
public enum MembershipTypes
{
Type1,
Type2,
Type3
}
public MembershipTypes _membershipTypes {get; set; }
//controller
[HttpPost]
public IActionResult Create([Bind("Id","Name","_membershipTypes")] Customers customers)
{
if (ModelState.IsValid)
{
_context.Add(customers);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Return View(customers);
}
//view
<div class="row">
<div class="col-md-6">
<form asp-action="Create">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
#Html.DropDownList("_membershipTypes",
new SelectList(Enum.GetValues(typeof(MembershipTypes))),
"Select membership type",
new { #class = "form-control" })
</div>
<input type="submit" value="Submit!" />
</form>
</div>
</div>
You need to show more about the relationships(one-to-one,one-to-many) of your models.
The parameters of your post action need to correspond with the model of your view,use NewCustomerviewModel instead of Customers.
The dropdownlist shows the type of name and pass id as value to action, so your asp-for of dropdown list needs to be set for an id or id list.
Refer to my demo which pass id list of MembershipTypes to action using multiple select.
1.My ViewModel NewCustomerviewModel,
public class MembershipTypes
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class NewCustomerviewModel
{
public int[] SelectMembershipTypesId { get; set; }
public Customers Customers { get; set; }
}
public class Customers
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
}
2.Create GET action
public IActionResult Create()
{
var model = new NewCustomerviewModel()
{
Customers = new Customers()
{
MembershipTypes = _context.MembershipTypes.ToList()
},
};
return View(model);
}
3.Create POST action
[HttpPost]
public async Task<IActionResult> Create(NewCustomerviewModel viewmodel)
{
if (ModelState.IsValid)
{
viewmodel.Customers.MembershipTypes= _context.MembershipTypes
.Where(m =>viewmodel.SelectMembershipTypesId.Contains(m.Id))
.ToList();
_context.Add(viewmodel.Customers);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(viewmodel);
}
4. Create View
#Html.DropDownListFor(m => m.SelectMembershipTypesId,
new SelectList(Model.Customers.MembershipTypes, "Id", "Name"), "Select Membership Type",
new { #class = "form-control", #multiple = "multiple" })
I have the following view model code:
public class TestCheckboxlistParentModel
{
public TestCheckboxlistParentModel()
{
CBL = new TestCheckboxlistModel();
}
public TestCheckboxlistModel CBL { get; set; }
}
public class TestCheckboxlistModel
{
public string TextField { get; set; }
public IList<string> SelectedFruits { get; set; }
public IList<SelectListItem> AvailableFruits { get; set; }
public TestCheckboxlistModel()
{
SelectedFruits = new List<string>();
AvailableFruits = new List<SelectListItem>();
}
}
controller:
public ActionResult TestCheckboxlist()
{
var model = new TestCheckboxlistParentModel
{
CBL = new TestCheckboxlistModel()
{
AvailableFruits = GetFruits()
}
};
return View(model);
}
[HttpPost]
public ActionResult TestCheckboxlist(TestCheckboxlistParentModel model)
{
if (ModelState.IsValid)
{
// Save data to database, and redirect to Success page.
return RedirectToAction("Success");
}
//model.AvailableFruits = GetFruits();
return View(model);
}
public ActionResult Success()
{
return View();
}
private IList<SelectListItem> GetFruits()
{
return new List<SelectListItem>
{
new SelectListItem {Text = "Apple", Value = "1"},
new SelectListItem {Text = "Pear", Value = "2"},
new SelectListItem {Text = "Banana", Value = "3"},
new SelectListItem {Text = "Orange", Value = "4"},
};
}
partial view:
#model Web.ViewModels.TestCheckboxlistModel
<div class="form-group">
#Html.LabelFor(model => model.TextField)
<div class="col-md-10">
#Html.EditorFor(model => model.TextField)
</div>
</div>
#foreach (var item in Model.AvailableFruits)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="#Html.IdFor(p=>p.SelectedFruits)"
value="#item.Value" /> #item.Text
</label>
</div>
}
view:
#model Web.ViewModels.TestCheckboxlistParentModel
#{
ViewBag.Title = "TestCheckboxlist";
Layout = "~/Views/Shared/_LayoutApplicationDriver.cshtml";
}
#using (Html.BeginForm())
{
#Html.Partial("TestPartialCheckboxlist", Model.CBL, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "CBL" } })
<div class="form-group text-center">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
}
Problem is SelectedFruits always does not have any elements in post method. The same code work correctly, if I don't use nested Partial view. Property TextField works fine with Partial
PS. It's not a dublicate of How to make Check Box List in ASP.Net MVC question. That question is a base of my answer. In my case, I need to have checkboxlist in partial view, where it does not work!
You use of name="#Html.IdFor(p => p.SelectedFruits)" generates name="CBL_SelectedFruits", but in order to bind to your model, you would need name="CBL.SelectedFruits" (note the . dot, not _ underscore) which you could generate using
name="#Html.NameFor(p => p.SelectedFruits)"
However there are other issues with your code. Your not strongly binding to your model, you get no validation, your generating a IList<SelectListItem> for property AvailableFruits when you don't need it (it could be just IList<string> AvailableFruits, and most importantly, if you return the view, all the checkboxes the user checked are lost (all checkboxes will be unchecked).
Change your view models so that you can strongly bind to your properties
public class FruitVM
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class ParentVM
{
public string TextField { get; set; }
public List<FruitVM> Fruits { get; set; }
}
and in the GET method
ParentVM model = new ParentVM
{
Fruits = new List<FruitVM>{
new FruitVM{ Name = "Apple" },
new FruitVM{ Name = "Pear" },
....
}
};
return View(model);
and create an EditorTemplate for FruitVM - in /Views/Shared/EditorTemplates/FruitVM.cshtml
#model FruitVM
#Html.CheckBoxFor(m => m.IsSelected)
#Html.LabelFor(m => m.IsSelected, Model.Name)
and in the view
#Html.ParentVM
....
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.TextField)
#Html.EditorFor(m => m.TextField)
#Html.EditorFor(m => m.Fruits)
<input type="Submit" value="Save" />
}
The EditorFor() method will generate the correct html for each item in your collection.
Then in the POST method, you can get the selected items with
[HttpPost]
public ActionResult TestCheckboxlist(ParentVM model)
{
....
List<string> selectedFruits = model.Fruits.Where(x => x.IsSelected);
I have been trying to get two models to appear in a single view using ViewModels but am failing.
I have simple view with 3 fields right now (Comment, Name, Department) and and a model to match it. I have a controller that returns an empty view and when you submit the form, the empty model is filled in and passed back to the controller. I now want to turn the department field into a drop down and have deduced (maybe incorrectly?) that I should create another model with the static values in it and then pass the ViewModel to the view via the controller but when I attempt to do this, it fails:
View:
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="fieldset">
<fieldset>
<legend>CommentDb</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Comment)
</div>
<div>
#Html.TextAreaFor(model => model.Comment, new {style = "width: 900px; height:200px;", autocomplete = "off" })
#Html.ValidationMessageFor(model => model.Comment)
</div>
<div class="editor-label">
#Html.Label("Your Name")
#*#Html.LabelFor(model => model.CommentByName)*#
#Html.TextBoxFor(model => model.CommentByName, new { autocomplete = "off", placeholder = "Optional" } )
#Html.ValidationMessageFor(model => model.CommentByName)
</div>
<div class="editor-label">
#Html.Label("Your Department", new { #class = "display-label" })
#*#Html.LabelFor(model => model.Department)*#
#Html.TextBoxFor(model => model.Department, new { autocomplete = "off", placeholder = "Optional" })
#Html.ValidationMessageFor(model => model.Department)
</div>
</fieldset>
<br />
<br />
</div>
<div>
<input type="submit" value="Create" id="submit"/>
</div>
}
Department drop down model:
namespace SuggestionBox.Models
{
public class DropDownModel
{
public String Departments { get; set; }
public String SetDropDownList()
{
Departments = "Engineering";
return Departments;
}
}
}
Database model:
namespace SuggestionBox.Models
{
public class CommentModel
{
[Key]
public int CommentiD { get; set; }
public string CommentByName { get; set; }
public string Department { get; set; }
[Required]
public string Comment { get; set; }
public DateTime InsertDate { get; set; }
}
}
namespace SuggestionBox.Models
{
public class CommentDbContext : DbContext
{
public CommentDbContext() : base()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<CommentDbContext, SuggestionBox.Migrations.Configuration>());
}
public DbSet<CommentModel> Comments { get; set; }
}
}
My attempted ViewModel:
namespace SuggestionBox.ViewModels
{
public class SuggestionBoxViewModel
{
public CommentModel Comments { get; set; }
public DropDownModel Departments { get; set; }
public SuggestionBoxViewModel()
{
Departments = new DropDownModel();
Departments.SetDropDownList();
Comments = new CommentModel();
}
}
}
The Controller:
public ViewResult Index()
{
SuggestionBoxViewModel vm = new SuggestionBoxViewModel();
return View(vm);
}
In return View(vm);, the IDE says: Arguement type 'SuggestionBox.ViewModels.SuggestionBoxViewModel' is not assignable to the model type 'SuggestionBox.Models.CommentModel'
Any idea what I am doing wrong here?
Cheers.
You are making a simple task into something overly complex. Your view model should contain only the properties used in the view, and should not contain methods. Populating your view model properties is the responsibility of the controller.
View model
public class CommentModelVM
{
[Required]
public string Comment { get; set; }
public string CommentByName { get; set; }
[Display(Name="Your Department")] // add attributes associated with the view
public string Department { get; set; }
public SelectList DepartmentList { get; set } // to populate the dropdown options
}
Controller
public ActionResult Create()
{
CommentModelVM model = new CommentModelVM();
ConfigureViewModel(model);
return View(model);
}
public ActionResult Create(CommentModelVM model)
{
if (!ModelState.IsValid())
{
// Repopulate options and return view
ConfigureViewModel(model);
return View(model);
}
// Save and redirect
}
private void ConfigureViewModel(CommentModelVM model)
{
List<string> departments = // create your list of departments here (from database or static list)
model.DepartmentList = new SelectList(departments);
}
View
....
#Html.LabelFor(m => m.Department)
#Html.DropDownListFor(m => m.Department, Model.DepartmentList)
....
I just want to start by saying that generally it is a bad idea to name properties or classes for our ViewModels out the view controls that they are bound to. For example: DropDownModel. Doing this creates confusion since Models and ViewModels don't represent a UI component they represent entities and data that the view uses to render its UI controls.
With that being said to answer you question I don't see the need for a ViewModel class to represent the static list of departments for your dropdown. I think you should just add a new list of departments to your SuggestionBoxViewModel class like this:
namespace SuggestionBox.ViewModels
{
public class SuggestionBoxViewModel
{
public CommentModel Comments { get; set; }
public IEnumerable<string> Departments { get; set; }
public string SelectedDepartment { get; set; }
public SuggestionBoxViewModel()
{
Departments = new [] {"Engineering","Sales"};
Comments = new CommentModel();
}
public int CommentiD
{
get { return Comments.CommentiD; }
}
public string CommentByName
{
get { return Comments.CommentByName; }
}
}
}
Then in your view all you have to do is bind the dropdown to the list of departments. Like this:
At the top of your view:
#model SuggestionBox.ViewModels.SuggestionBoxViewModel
Then where you want the dropdown to display:
#Html.DropDownListFor(m => m.SelectedDepartment, new SelectList(Model.Departments))
And that's it! I hope this helps.
Your View seems to expect a Comment Model.
If you wanted to bind to a ViewModel, then you would have to implement all the properties that Comment exposes.
So your ViewModel might look like this:
namespace SuggestionBox.ViewModels
{
public class SuggestionBoxViewModel
{
public CommentModel Comments { get; set; }
public DropDownModel Departments { get; set; }
public SuggestionBoxViewModel()
{
Departments = new DropDownModel();
Departments.SetDropDownList();
Comments = new CommentModel();
}
public int CommentiD
{
get { return Comments.CommentiD; }
}
public string CommentByName
{
get { return Comments.CommentByName; }
}
...etc.
}
}
I have the following cshtml form
#using (Html.BeginForm(Html.BeginForm("Create", "UserRole", Model, FormMethod.Post)))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Role</legend>
<div class="editor-label">
#Html.Label(Model.User.UserName)
</div>
<div class="editor-field">
#Html.CheckBoxList(Model.CheckboxList)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
And I wish to get the Model.CheckboxList selected Items in my action.
I have the following Create Action in my Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(UserRoleViewModel userRoleViewModel)
{
if (ModelState.IsValid)
{
//_context.Role.Add(role);
//_context.SaveChanges();
//return RedirectToAction("Index");
}
return View(viewModel);
}
However the viewModel.CheckboxList is 0.
How can I pass the selected values of the checkboxlist, and also the Model.User to the Controller Action?
My ViewModel looks like this :-
public User User { get; set; }
public IEnumerable<Role> RoleList { get; set; }
public List<UserRoleViewModel> UserList { get; set; }
public IEnumerable<SelectListItem> CheckboxList { get; set; }
public UserRoleViewModel()
{
}
public UserRoleViewModel(User user, IEnumerable<Role> roleList )
{
User = user;
RoleList = roleList;
}
Thanks for your help and time!
UPDATE ----------- After reading this post enter link description here, I tried to adapt my code to follow the example, but I am still finding problems with this updated code.
Now I have the following :-
cshtml :-
#model IEnumerable<MvcMembership.ViewModels.RoleCheckboxListViewModel>
#using (Html.BeginForm())
{
#Html.EditorForModel()
<input type="submit" value="OK" />
}
Views/Role/EditorTemplates/RoleCheckboxListViewModel.cshtml
#model MvcMembership.ViewModels.RoleCheckboxListViewModel
#Html.HiddenFor(x => x.RoleId)
#Html.HiddenFor(x => x.RoleName)
<div>
#Html.CheckBoxFor(x => x.Checked)
#Html.LabelFor(x => x.Checked, Model.RoleName)
</div>
ViewModels :-
public class RoleCheckboxListViewModel
{
public string RoleId { get; set; }
public string RoleName { get; set; }
public bool Checked { get; set; }
}
and the controller action is as follows :-
public ActionResult Create(int? uid)
{
var checkBoxList = new[]
{
new RoleCheckboxListViewModel() {
RoleId = "1", Checked = true, RoleName = "item 1" },
new RoleCheckboxListViewModel() {
RoleId = "2", Checked = true, RoleName = "item 2" },
new RoleCheckboxListViewModel() {
RoleId = "3", Checked = true, RoleName = "item 3" },
};
return View(checkBoxList);
}
The problem I have now is that on the Create.cshtml. I cannot see the checkboxlist, but only 123 displayed as well as the OK button.
Any help would be very much appreciated cause I am at a dead end at the moment.
I've accomplished this with the following parts:
1) A view model for the child element that adds the bool property that will represent whether or not the checkbox is checked in the View later... ie:
public class CategoryViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public bool Assigned { get; set; }
}
2) A view model for the parent element that adds a collection property for this new child element view model, ie:
public class ManufacturerViewModel
{
public Manufacturer Manufacturer { get; set; }
public IList<CategoryViewModel> Categories { get; set; }
public ManufacturerViewModel()
{
Categories = new List<CategoryViewModel>();
}
}
3) A service layer method for getting a list of all child elements, while also setting the bool property for each ("Assigned" in my example). To be used by your controller.
public IList<CategoryViewModel> GetCategoryAssignments(Manufacturer mfr)
{
var categories = new List<CategoryViewModel>();
foreach (var category in GetCategories())
{
categories.Add(new CategoryViewModel
{
ID = category.ID,
Name = category.Name,
Assigned = mfr.Categories.Select(c => c.ID).Contains(category.ID)
});
}
return categories;
}
4) A method for updating the parent item's collection based on your checkboxlist selections. To be used by your controller.
public void UpdateCategories(string[] selectedCategories, ManufacturerViewModel form)
{
if (selectedCategories == null)
selectedCategories = new string[] { };
var selectedIds = selectedCategories.Select(c => int.Parse(c)).ToList();
var assignedIds = form.Manufacturer.Categories.Select(c => c.ID).ToList();
foreach (var category in GetCategories())
{
if (selectedIds.Contains(category.ID))
{
if (!assignedIds.Contains(category.ID))
form.Manufacturer.Categories.Add(category);
}
else
{
if (assignedIds.Contains(category.ID))
form.Manufacturer.Categories.Remove(category);
}
}
}
5) Modifications to your Create/Edit view. ie:
#Html.EditorFor(model => model.Categories)
You must also add this so that the original assigned values are included in post data. You'll have to add a HiddenFor for each property that you have set as Required through validation.
for (int i = 0; i < Model.Manufacturer.Categories.Count; i++)
{
#Html.HiddenFor(model => model.Manufacturer.Categories[i].ID);
#Html.HiddenFor(model => model.Manufacturer.Categories[i].Name);
}
6) And finally, a new EditorTemplate for your child view model element. ie:
#model YourProject.ViewModels.CategoryViewModel
<li>
<input type="checkbox"
id="#string.Format("cb{0}{1}", #Model.Name, #Model.ID)"
name="selectedCategories" //Notice this name corresponds to string[] selectedCategories so that it can be extracted from the post data
value="#Model.ID"
#(Html.Raw(Model.Assigned ? "checked=\"checked\"" : "")) />
<label for="#string.Format("cb{0}{1}", #Model.Name, #Model.ID)">#Model.Name</label>
#Html.HiddenFor(model => model.ID)
</li>
Hopefully my own application gives you a better idea of how to solve this issue.
Store your selected value into the variable as follows, and pass it to an hidden field, then you can access it easily
var modelSelected = document.getElementById("modelName");
document.getElementById('selectedModel').value =
modelSelected.options[modelSelected.selectedIndex].text;
<input id="selectedModel" name="selectedModel" type="hidden" runat="server" />
I have got a drop downlist that, and i need to set the selected value in a view ,later on when the user selected any item in drop down list , i need to pass that one to model.. I am binding dropdown list in controller like this way ..
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
var itemsforDropdown = new List<SelectListItem> {
new SelectListItem{ Text = "Amount" , Value = "Amount"},
new SelectListItem{Text= "Pound", Value ="Pound"},
new SelectListItem {Text ="Percent", Value ="Percent"}
};
ViewBag.ItemsforDrop = itemsforDropdown;
//ViewData["listitem"] = itemsforDropdown;
return View("DdlCrossFields");
}
and I have got a property in my model like this...
public class CrossFieldValidation
{
[ValueMustbeInRange]
public string DDlList1
{ get; set; }
public string SelectedValue
{ get; set; }
// [Required(ErrorMessage = "Quantity is required")]
[Display(Name = "Quantity:")]
public string TxtCrossField
{ get; set; }
}
and this is my view ...
#using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
{
#Html.ValidationSummary(true)
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownList("ItemsforDrop", ViewBag.ItemsforDrop as SelectList,"Select A state", new {id= "State"})
//here i need to get the selected value and i need to pass the this on to model fro future purpose "
<input id="PostValues" type="Submit" value="PostValues" />
}
would any one pls help on this ...
many thanks.....
I'm finding it hard to figure out exactly what you are trying to achieve here but I would set up the page like below.
This way, the CrossFieldValidation is sent to the PostValues with the selected value in the list
Model
public class CrossFieldValidation
{
[ValueMustbeInRange]
public string DDlList1
{ get; set; }
/* add the items list into the model */
public IEnumerable<SelectListItem> Items
{ get; set; }
public string SelectedValue
{ get; set; }
[Display(Name = "Quantity:")]
public string TxtCrossField
{ get; set; }
}
Controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
var model = new CrossFieldValidation {
Items = new [] {
new SelectListItem{ Text = "Amount" , Value = "Amount"},
new SelectListItem{Text= "Pound", Value ="Pound"},
new SelectListItem {Text ="Percent", Value ="Percent"}
}
};
return View(model);
}
View
#model CrossFieldValidation
#using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
{
#Html.ValidationSummary(true)
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownListFor(m=>m.SelectedValue, new SelectList(Model.Items, "Value", "Text"))
<input id="PostValues" type="Submit" value="PostValues" />
}
In your controller [HttpPost] action add below.
string selectedVal = Request.Form["ItemsforDrop"].ToString();