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);
Related
I am a new to MVC and still learning! I am trying to create a very basic App in my web which allows users to convert money value according to their preference. I made the web APi and was successful to call the service to my forms. However, in my controller I managed to get the currencies (names) to the index view, but cannot post the form back once entering a value in the text box to generate the partial view! What am I doing wrong in my codes?!
Currency Controller
namespace MVC_ATM.Controllers
{
public class CurrencyController : Controller
{
[HttpGet]
// GET: Currency
public ActionResult Index()
{
CurrenciesClient Cur = new CurrenciesClient();
var listCurrency = Cur.findAll();
SelectList list = new SelectList(listCurrency,"Id", "CurrencyName");
ViewBag.listCurrencies = list;
return View();
}
[HttpPost]
public ActionResult Index(Currencies cur)
{
if (!ModelState.IsValid)
{
string errors = string.Join("<br />", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
return new ContentResult { Content = errors };
var rate = Convert.ToDecimal(cur.ConversionRate);
if (cur.CurrencyName == cur.CurrencyName)
{
ModelState.AddModelError("CurrencyCountry", "Can't make the conversion for the same value");
}
else if (cur.CurrencyName != cur.CurrencyName)
{
foreach (var currency in cur.CurrencyName)
{
ViewBag.Theresult = rate * cur.Value;
}
return PartialView("_CurrencyValue");
}
}
return View();
}
}
}
Currencies Model
namespace Project.Model
{
public class Currencies
{
public int Id { get; set; }
public string CurrencyName { get; set; }
public string CurrencyCountry {get; set;}
public decimal Value { get; set; }
public string ConversionRate { get; set; }
}
}
Index View
#model Project.Model.Currencies
#{
ViewBag.Title = "Index";
}
<h2>Currency</h2>
<body>
<div class="converter">
Convert: #Html.TextBoxFor(m => m.ConversionRate, new { #size = "5" })
<div class="form-group">
#Html.Label("Convert from", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Currency List", ViewBag.listCurrencies as SelectList, "Please Select a currency")
</div>
</div>
<div class="form-group">
#Html.Label("Convert to", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Currency List", ViewBag.listCurrencies as SelectList, "Please Select a currency")
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Convert</button>
</div>
</div>
</body>
Couple of things to notice, is the POST action and missing form tag in the view . You created a POST action that accepts Currencies model but the form doesn't post that. Only ConversionRate will bind to the model. To get the "Currency From" and "Currency To" and the "Conversion Rate" you will require a different approach/small changes.
ConversionModel.cs a new Model for index page that will capture your required fields.
public class ConversionModel
{
[Required]//decimal would be better but up to you requirement
public decimal ConversionRate { get; set; }
[Required]
public int FromCurrencyId {get;set;}
public SelectList FromCurrencies {get;set;}
[Required]
public int ToCurrencyId {get;set;}
public SelectList ToCurrencies {get;set;}
}
Get: while there is nothing wrong with what you've done, lets use a model approach and tightly bind it.
public ActionResult Index()
{
CurrenciesClient Cur = new CurrenciesClient();
var listCurrency = Cur.findAll();
ConversionModel model = new ConversionModel();
model.FromCurrencies = new SelectList(listCurrency,"Id", "CurrencyName");
model.ToCurrencies = new SelectList(listCurrency,"Id", "CurrencyName");
return View(model);
}
Post: Important thing here to notice is the SelectList will not be posted back. Only the ConversionRate, FromCurrencyId and ToCurrencyId are sent back not the Lists. If error occurs you will need to rebuild the lists and send it back in the model.
[HttpPost]
public ActionResult Index(ConversionModel curModel)
{
if(ModelState.IsValid)
{
if(curModel.FromCurrencyId ==curModel.ToCurrencyId)
{
//do something if same currecnies and return.
}
else
{
//Get the currencyList with rates from db
//use currency ToCurrencyId and FromCurrencyId to fetch the 2 currencies
// perform conversion with curModel.ConversionRate with existing logic
}
}
//Don'f forget to rebuild the Select Lists...
return View(curModel);
}
View:
#model Project.Model.ConversionModel
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("Index", "Currency", FormMethod.Post)
{
#Html.TextBoxFor(m => m.ConversionRate, new { #size = "5" })
#* Please check the syntax *#
#Html.DropDownListFor(m => m.FromCurrencyId , Model.FromCurrencies as SelectList)
#Html.DropDownListFor(m => m.ToCurrencyId , Model.ToCurrencies as SelectList)
<button type="submit" class="btn btn-primary">Convert</button>
}
Not a CUT_COPY_PASTE. please do check for errors if any. It is only an approach.
ajax POST probably the next thing to learn... Let us know.
You need to put your items inside a form like this:
#using (Html.BeginForm("Index", "Currency", FormMethod.Post)
{
// Your form items
}
How can I create a view that has multiple models that need validation and also has multiple forms to submit all within the same view?
I have the solution below. As I was typing it up I was able to figure it out, so hopefully it will help someone else. If others have a better approach or comments, please feel free to post!
I have a view that contains a ViewModel, which combines 2 models. Here is the ViewModel, along with the other classes:
public class PlayerFormViewModel
{
public PlayerFormEnglish PlayerFormEnglish { get; set; }
public PlayerFormSpanish PlayerFormSpanish { get; set; }
}
public class PlayerFormEnglish : PlayerFormInformation { }
public class PlayerFormSpanish : PlayerFormInformation { }
public class PlayerFormInformation
{
[Required(ErrorMessage = "First name is a required field.")]
[Display(Name = "First name")]
public string FirstName { get; set; }
// Used as a dropdown in the view
[Display(Name = "Gender")]
public IEnumerable<SelectListItem> Gender{ get; set; }
}
My main view contains the ViewModel and 2 forms:
#model Namespace.Models.PlayerFormViewModel
#using (Html.BeginForm("PlayerTest", "Profile"))
{
#Html.AntiForgeryToken()
<h3>English</h3>
#Html.LabelFor(m => m.PlayerFormEnglish.FirstName)
#Html.TextBoxFor(m => m.PlayerFormEnglish.FirstName)
#Html.ValidationMessageFor(m => m.PlayerFormEnglish.FirstName)
#Html.LabelFor(m => m.PlayerFormEnglish.Gender)
#Html.DropDownListFor(m => m.PlayerFormEnglish.Gender, new SelectList(Model.PlayerFormEnglish.Gender, "Value", "Text"))
<button type="submit" class="btn btn-default" name="ButtonType" value="SaveEnglishForm">Save</button>
}
#using (Html.BeginForm("PlayerTest", "Profile"))
{
#Html.AntiForgeryToken()
<h3>Spanish</h3>
#Html.LabelFor(m => m.PlayerFormSpanish.FirstName)
#Html.TextBoxFor(m => m.PlayerFormSpanish.FirstName)
#Html.ValidationMessageFor(m => m.PlayerFormSpanish.FirstName)
#Html.LabelFor(m => m.PlayerFormSpanish.Gender)
#Html.DropDownListFor(m => m.PlayerFormSpanish.Gender, new SelectList(Model.PlayerFormEnglish.Gender, "Value", "Text"))
<button type="submit" class="btn btn-default" name="ButtonType" value="SaveSpanishForm">Save</button>
}
When the page first loads, I pre-populate the fields like this:
[HttpGet]
public ActionResult PlayerTest()
{
PlayerFormViewModel model = new PlayerFormViewModel();
model.PlayerFormEnglish = new PlayerFormEnglish();
model.PlayerFormSpanish = new PlayerFormSpanish();
model.PlayerFormEnglish.FirstName = "Brad";
List<SomeObject> genderList = GetDataForDropdown();
model.PlayerFormEnglish.Gender = ConvertData(genderList);
model.PlayerFormSpanish.Gender = ConvertData(genderList);
return View(model);
}
Finally, I validate and update the saved form when a user clicks the save button:
[HttpPost]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public ActionResult PlayerTest(PlayerFormViewModel model, string ButtonType)
{
if (ButtonType.Equals("SaveEnglishForm"))
{
if (ModelState.IsValid)
{
return RedirectToAction("SuccessfulSave", "Profile");
}
model.PlayerFormSpanish = new PlayerFormSpanish();
}
else
{
if (ModelState.IsValid)
{
return RedirectToAction("SuccessfulSave", "Profile");
}
model.PlayerFormEnglish = new PlayerFormEnglish();
}
// I can repopulate the fields here just as before
model.PlayerFormEnglish.FirstName = "Brad";
List<SomeObject> genderList = GetDataForDropdown();
model.PlayerFormEnglish.Gender = ConvertData(genderList);
model.PlayerFormSpanish.Gender = ConvertData(genderList);
// Return model which will mark the required fields in the UI
return View(model);
}
Hope this helps!
I have ModelView which I have created for purpose to create new record instance via view-- razor form. In controller I need to assign list data to ViewModel; IEnumerable and then pass this model along with with list data (of CategoryType) which then in view I need to populate in drop-down list, followed by ID of selected CategoryType send back to controller along with other data.
I have assign IEnumerable value to model in controller but not sure is correct and how to do rest part in view ???
View Model - CompanyProfileModelView
public class CompanyProfileModelView
{
public Company _Company { get; set; }
public IEnumerable<CategoryType> _CategoryType { get; set; }
}
Model Class
public class CategoryType
{
public int CategoryTypeID { get; set; }
public string CategoryTitle { get; set; }
public ICollection<Company> Companies { get; set; }
}
Controller Class
[HttpGet]
public ActionResult CreateCompany()
{
var _listData = _appFunctions.GetAllCategory();
var _model = new CompanyProfileModelView
{
_CategoryType = _listData
??????????????
};
return PartialView("_CreateNewCompanyPartial", _model);
}
[HttpPost]
public ActionResult CreateCompany(CompanyProfileModelView _model)
{
try
{
if (ModelState.IsValid)
{
//my code will be here to read for input data
}
}
catch (DataException ex)
{
ModelState.AddModelError("", "Unable To Create New Function Navigation" + ex);
}
return RedirectToAction("Home");
}
View
#model App.DAL.Model.CompanyProfileModelView
#using (Html.BeginForm("CreateCompany", "CompanyProfile", FormMethod.Post, new { id = "NewFunctionNavigationForm" }))
{
<div class="form-group">
#Html.LabelFor(#model => #model._Company.CompanyName, new { #class = "control-label col-md-2" })
<div class="form-group">
#Html.EditorFor(#model =>#model._Company.CompanyName)
#Html.ValidationMessageFor(#model=>#model._Company.CompanyName)
</div>
</div>
<div class="form-group">
// need help here for dropdown of CategoryType list
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
Since DropDownList uses IEnumerable<SelectListItem>, change the view model to
public class CompanyProfileModelView
{
public Company Company { get; set; }
public SelectList CategoryList { get; set; }
}
and assuming Company model contains
[Display(Name="Category")]
public int? CategoryType { get; set; }
Controller
[HttpGet]
public ActionResult CreateCompany()
{
var listData = _appFunctions.GetAllCategory();
var model = new CompanyProfileModelView
{
CategoryList = new SelectList(listData, "CategoryTypeID ", "CategoryTitle")
};
return View(model);
}
[HttpPost]
public ActionResult CreateCompany(CompanyProfileModelView model)
{
if (!ModelState.IsValid)
{
// Re-assign select list if returning the view
var listData = _appFunctions.GetAllCategory();
model.CategoryList = new SelectList(listData, "CategoryTypeID ", "CategoryTitle");
return View(model)
}
// Save and redirect
}
View
#model App.DAL.Model.CompanyProfileModelView
#using (Html.BeginForm()) // Note, no parameters required in this case
{
....
#Html.LabelFor(m => m.Company.CategoryType, new { #class = "control-label col-md-2" })
#Html.DropDownListFor(m => m.Company.CategoryType, Model.CategoryList, "--Please select--")
#Html.ValidationMessageFor(m => m.Company.CategoryType)
.....
<input type="submit" value="Create" class="btn btn-default" />
}
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();