I have a dropdownlist,while editing i need to set the current value.But my codes are not working.
My view look like follow
#Html.DropDownListFor(m => m.id, Model.ddls, "Please Select", new { #class = "form-control" })
Model
public string id { get; set; }
public List<SelectListItem> ddls { get; set; }
Controller
public IActionResult editmaster(string id, string sec)
{
master m = new master();//here is my model
m.ddls = PopulateDDLDataSet(ds.Tables[1], "companyname", "companyid");//ddls is my object and populateddldataset is my methode to fill the list
return View(m);
}
ddls is the selectedlistitems that i have filled from controller,that work fine.But the value which in in id not set on the list
Checked the code and its working for me. Could you provide more details about your model?
Wanted to say that you can make similar things by using built-in razor tag helpers that is more clear.
Documentation for select
Example of using tag helper in your code:
<select class="form-control" asp-for="#Model.id" asp-items="Model.ddls">
<option selected>Please select</option>
</select>
please follow this, it may be this code help you.
Model Code
public class testmdl
{
public string id { get; set; }
public IEnumerable<SelectListItem> ddls { get; set; }
}
Controller Code
//------ without using entity for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
IEnumerable<SelectListItem> companyList = new List<SelectListItem>
{
new SelectListItem { Value = "001", Text = "StackOverflow1" },
new SelectListItem { Value = "002", Text = "StackOverflow2" }
};
obj.ddls =companyList ;
return View(obj);
}
//--- using entity framework for select list items
public IActionResult Test()
{
testmdl obj=new testmdl();
List<SelectListItem> companyList = new SelectList(db.yourcompanytable, "companyid", "comapnyname").ToList();
obj.ddls =companyList ;
return View(obj);
}
View Code
<select id="id1" name="id1" asp-for="id" asp-items="#Model.ddls" class="form-control">
<option value=#null>--- Select --- </option>
</select>
<span asp-validation-for="id" style="color:red;"></span>
In my case none of the above answers work(I don't clearly understand what went wrong for me) ,but finally i achieved in an alternative way.Below my codes.Thanks for all the supports.
<script>
document.getElementById("id").value =#Model.id;
</script>
Put this after binding the dropdownlist.
Related
I'm using ASP.NET Core v3 MVC with Visual Studio 2019 Enterprise.
I have database like this:
I'm using database first approach to generate models for that database.
After that I'm adding following type of controller for product_info table:
Which will also generate Views. My question is - how can I display attributes from other tables in drop-down of Create View.
Here is example of what I mean:
I don't need complete solution, though it could be useful, any hints or pointers on how to do it would suffice.
You can create a viewmodel to display attributes in other model.
ViewModel:
public class ViewModel
{
public IEnumerable<SelectListItem> Model1Items{ get; set; }
public int SelectedId { get; set; }
}
Controller:
var items = (from m in db.Model1s
select new SelectListItem{
Value = m.Id,
Text = m.Name
}).ToList();
var vm = new ViewModel();
vm.Model1Items = new SelectList(items, "Value", "Text");
View:
#Html.DropDownListFor(model => model.SelectedId, Model.Model1Items, "--Select--")
This is full solution with fix for various problems I've encountered:
MODEL
Create folder in your project and call it ViewModel
Create class in that folder and call it ProductInfoViewModel.cs.Here is full content of ProductInfoViewModel.cs:
namespace ProductTest.ViewModels
{
public class ProductInfoViewModel
{
public int ProductId { get; set; }
public IEnumerable<SelectListItem> ProductName { get; set; } = new List<SelectListItem>();
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> CategoryName { get; set; } = new List<SelectListItem>();
public int SubcategoryId { get; set; }
public IEnumerable<SelectListItem> SubcategoryName { get; set; } = new List<SelectListItem>();
}
}
Initialization with new List<SelectListItem>(); is important so you don't get NULL reference error.
CONTROLLER
Under // GET: ProductInfoes/Create add logic for getting data from database and loading it to ProductInfoViewModel object :
public IActionResult Create() {
// Hooks on databse to get list of Products
var products = (from m in _context.Product
select new SelectListItem
{
Value = m.ProductId.ToString(),
Text = m.ProductName
}).ToList();
// Create new instance of our ViewModels.ProductInfoViewModel(()
var vm = new ViewModels.ProductInfoViewModel();
// Fill in ProductName in ProductInfoViewModel with list fetch from database
vm.ProductName = new SelectList(products, "Value", "Text").Where(products => products != null);
// Do same thing to Category and Subcategory
var categories = (from m in _context.Category
select new SelectListItem{
Value = m.CategoryId.ToString(),
Text = m.CategoryName
}).ToList();
vm.CategoryName = new SelectList(categories, "Value", "Text").Where(categories => categories != null);
var subcategories = (from m in _context.Subcategory
select new SelectListItem
{
Value = m.SubcategoryId.ToString(),
Text = m.SubcategoryName
}).ToList();
vm.SubcategoryName = new SelectList(subcategories, "Value", "Text").Where(subcategories => subcategories != null);
//Pass that model to View
return View(vm);
}
VIEW
than go to Views/ProductInfoes/Create.cshtml file.
Add following code:
#model ProductTest.ViewModels.ProductInfoViewModel
#{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Create</h1>
<h4>ProductInfo</h4>
<hr />
<form asp-action="Create">
#Html.DropDownListFor(model => Model.ProductId, Model.ProductName, "--Select--")
#Html.DropDownListFor(model => Model.CategoryId, Model.CategoryName, "--Select--")
#Html.DropDownListFor(model => Model.SubcategoryId, Model.SubcategoryName, "--Select--")
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
If you go to your Create page, something like:
https://localhost:44382/ProductInfoes/Create
and you will get this:
Click Create after you choose from dropdown. And if you go back to index page you'll see that product is successfully added on the list.
I have one dropdown in my MVC application.
I have a field in my model:
public IList<SexGenderModel> SexualOrientationList { get; set; }
class for SexGenderModel:
public class SexGenderModel
{
public int? MasterID { get; set; }
public string CodeDescription { get; set; }
public string SNOMED { get; set; }
}
In my view page I have used razor syntax
#Html.DropDownListFor(x => x.SexualOrientationList, new SelectList(Model.SexualOrientationList, "MasterID", "CodeDescription"), "--Select--", new { #class = "form-control input-sm"})
Every list item has their own SNOMED which I want to display in tooltip.
Please note I want to display tooltip for ListItem not for selected item of dropdown.
How can I achieve this with razor?
Any other option to map attributes to dropdownlist(Model.SexualOrientationList) from backend? How?
All you need to add attribute "title" to each item in dropdown
<select>
#foreach (var item in Model.SexualOrientationList)
{
<option title='#item.SNOMED' value="#item.MasterID">#item.CodeDescription</option>
}
</select>
Going further with #Khaled-Yosry 's answer:
#Ankita this DOES use Razor, so I'm not sure why you find yourself restricted.
If it's the <select> tag rendering you are worried about, you can append the necessary tags yourself:
All you need to add attribute "title" to each item in dropdown
<select name="#Html.NameFor(m => m.SexualOrientation)" id="#Html.IdFor(m => m.SexualOrientation)" class="form-control input-sm">
<option value="">--Select one--</option>
#foreach (var item in Model.SexualOrientationList)
{
<option title="#item.SNOMED" value="#item.MasterID" #(Model.SexualOrientation == item.MasterID ? "selected" : string.empty)>#item.CodeDescription</option>
}
</select>
Also, don't forget to include a property in your Model which will actually be bound to the selected value of the dropdown list:
public int SexualOrientation { get; set; }
I'm using this Bootstrap Multiselect and my problem is that I cant get the selected values on HttpPost on ASP.Net MVC.
Problems Encountered:
after clicking save, Only the first selected value is the present on
the model. (SOLVED)
after clicking save, Only the first selected value is the present on
the dropdownlist.
Sample.chtml:
#model SampleProject.Models.SampleViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.Selected, new SelectList(Model.List, "value", "text"), new { #class = "multiselect form-control", multiple = "multiple" })
<input type="submit" value="Save" />
}
Model:
public class SampleViewModel
{
public string[] Selected { get; set; }
public SelectList List { get; set; }
}
Controller:
public class DashboardController : Controller
{
public ActionResult Sample()
{
SampleViewModel model = new SampleViewModel();
model.List = new SelectList(new List<string>() { "1", "2", "3" });
return View(model);
}
[HttpPost]
public ActionResult Sample(SampleViewModel model)
{
model.List = new SelectList(new List<string>() { "1", "2", "3" });
return View(model);
}
}
Selection:
I cant get the selected values correctly on HttpPost
Code Behind/HttpPost: (Wrong)
After HttpPost: (Correct)
A <select multiple="multiple"> posts back an array of values (not a single value). You property Selected needs to be IEnumerable, for example
public string[] Selected { get; set; }
Side note: Since the text and value properties are the same, you can simplify you code by making the List property SelectList
public SelectList List { get; set; }
and then in the controller
model.List = new SelectList(new List<string>() { "1", "2", "3" })
(although its not clear why you would not use int)
Didn't see this answer anywhere, so to solve the issue with having only 1 item selected after the post back you need to use:
#Html.ListBoxFor(..
instead of #Html.DropDownListFor
There are similar questions and I have tried most of them. Instead of continuing to destroy the remaining code while conjuring demons from the similar past questions, I have decided to ask for help.
When I arrive at the AddMembership action I get a null value instead of the selected item. Below are the details.
View;
#using (Html.BeginForm("AddMembership", "WorkSpace", FormMethod.Post, new { data_ajax = "true", id = "frmAddMembership" }))
{
<div id="newMembershipDiv">
#Html.DropDownListFor(m => m.selectedID, new SelectList(Model.allInfo, "Value","Text",1), "Select!")
<input type="submit" value="Add" name="Command" />
</div>
}
Controller (I just want to see the selectedID or anything appear here.);
public ActionResult AddMembership(SelectListItem selectedID)
{
return View();
}
Model;
public class SomeModel
{
public SelectList allInfo { get; set; }
public SelectListItem selectedID { get; set; }
}
The Monstrosity which initializes the allInfo SelectList
model.allInfo = new SelectList(synHelper.getall().ToArray<Person>().Select(r => new SelectListItem {Text=r.Name, Value=r.prID.ToString() }));
synHelper.getAll() returns a List of the below class;
public class Person
{
public Guid prID { get; set; }
public string Name { get; set; }
}
The only thing that is posted to your action is a selectedID, which is a simple string. If you wander, in the request it looks as simple as:
selectedID=1234
Therefore it should be awaited for as a simple string. Adjust your action parameter:
public ActionResult AddMembership(string selectedID)
I created a model and i am trying to build something like when i click on submit button the values should be passed to controller which looks like
[HttpPost]
// i am getting checked property but not phoneno to controller
public ActionResult Confirm(Entity s)
{
return view();
}
My View
#model MvcApplication3.Models.Entity
#using ( Html.BeginForm("Confirm", "Home", FormMethod.Post))
{
#Html.CheckBoxFor(m=>m.checkedprop,
new
{
#class = "myCheckBox",
phoneno= "1234" //tried different ways none looks working for me
})
<input type="submit" id="ConfirmButton" />
}
Model
public class Entity
{
public bool checkedprop { get; set; }
public int phoneno { get; set; }
}
Your markup
#Html.HiddenFor(m=>m.phoneno)
and in your controller you can get
[HttpPost]
public ActionResult Confirm(Entity s, string phoneno)
{
return view();
}
Change
#Html.CheckBoxFor(m=>m.checkedprop,new {
#class = "myCheckBox",
phoneno= "1234" //tried different ways none looks working for me
})
to
#Html.CheckBoxFor(m=>m.checkedprop,new {#class = "myCheckBox"})
#{Model.phoneno = 1234}
#Html.HiddenFor(m => m.phoneno)
The reason yours didn't work is you were trying to set the phone number as an attribute of the checkbox. You need to submit that phone number as a separate field on the form. Since it's hardcoded, and the user isn't inputing it, instead of submitting it from a textbox (or whatever), you send it as a hidden field on the form.