I use #Html.DropDownList in a partial view for show the list of banks and render it in the Bank Branch view.
How can i get the selected Bank in #Html.DropDownList and fill the BankId in the BankBranchModel .
here is my code:
BankBranchModel :
public class BankBranchModel : BaseModel
{
public int? **BankID** { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
My partial view :
#Html.DropDownList("Banks", Model , "- Please Select -"})
BankBranch View:
#model MvcFirstSample.Models.BankBranchModel
#{
ViewBag.Title = "create";
}
<h2>create</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="editor-field">
**#Html.Action("GetAllBank", "BankBranch")**
</div>
GetAllBanks for return the Partial view:
public ActionResult GetAllBank()
{
var Banks = Context.Banks.ToList();
List<BankLookup> BankLookupList = new List<BankLookup>();
var listItems = new List<SelectListItem>();
foreach (var Bank in Banks)
{
listItems.Add(new SelectListItem { Text = Bank.Name, Value = Bank.Id.ToString()});
}
**return PartialView("BankLookup", listItems);**
}
Why you don't want to use ViewBag?
In your Partial View you can say:
#Html.DropDownList("listItems",(IEnumerable<SelectListItem>)ViewBag.listItems )
, then use Jquery to get selected item:
var selectBanks= $("#listItems");
var selectedOptionId = selectBanks.find("option:selected").val();
Then populate input for bankid assuming it has id of bankid:
$("#bankid").val(selectedOptionId);
Here is one way...
In your Partial View:
#Html.DropDownList("bank_list")
In your controller, populate the list by binding ids and values:
ViewBag.bank_list = new SelectList(listItems, "Text", "Value");
Related
i have a model :
public class studentmodel
{
public int id { get; set; }
public string name { get; set; }
}
i populate my dropdown :
// GET: dropdown/Test
public ActionResult Index()
{
List<SelectListItem> list = new List<SelectListItem>();
{
list.Add(new SelectListItem { Text = "saurav", Value = "1"});
list.Add(new SelectListItem {Text = "Rj", Value = "2" });
list.Add(new SelectListItem {Text = "rahul", Value = "3" });
ViewBag.studentlist = list;
}
return View();
}
[HttpPost]
public ActionResult Index(studentmodel s)
{
return View();
}
i have a controller action which is postback:
#using (Html.BeginForm("Index", "Test", FormMethod.Post))
{
#Html.DropDownListFor(m => m.name, (IEnumerable<SelectListItem>)ViewBag.studentlist, "select student");
<div>
<input type="submit" value="submit" />
</div>
<div> you have selected : #ViewBag.selected </div>
}
How do i get the text from my drop down list? Thanks
You need to use client side javascript as the change happens at the browser.
First change the markup a little bit to wrap the selection in a span.
<div> you have selected : <span id="selectedItem">#ViewBag.selected</span> </div>
Remove the #ViewBag.selected from the above line if your GET action is not really setting anything to that.
Now the script
$(function(){
$("#name").change(function(){
var selected = $(this).find("option:selected").text();
$("#selectedItem").text(selected);
});
});
This will read the selected option's Text and set that on our span.
If you want this text in the HttpPost action, you can add a new property to your view model
public class studentmodel
{
public int id { get; set; }
public string name { get; set; }
public string SelectedText{ get; set; }
}
And keep a hidden field inside the form
#Html.HiddenFor(s=>s.SelectedText)
Now, set the value of this using javascript set the value of this hidden field.
$(function(){
$("#name").change(function(){
var selected = $(this).find("option:selected").text();
//var selected = $("#name option:selected").text(); // another option
$("#selectedItem").text(selected);
$("#SelectedText").val(selected);
});
});
Now when you submit the form, the value of the hidden field SelectedText will also be submitted.
Model add one viewmodel as below
public class studentmodel
{
public int id { get; set; }
public string name { get; set; }
}
public class SomeViewModel
{
public string studentname {get; set;}
public SelectList studentlist {get; set;}
}
Updated
public ActionResult Index()
{
SomeViewModel Model = new SomeViewModel();
var studentlist = new List<SelectListItem>();
studentlist.Add(new SelectListItem() { Value = "1", Text = "saurav" });
studentlist.Add(new SelectListItem() { Value = "2", Text = "Rj" });
studentlist.Add(new SelectListItem() { Value = "3", Text = "rahul" });
Model.studentlist = new SelectList(studentlist, nameof(SelectListItem.Value), nameof(SelectListItem.Text));
return View(Model);
}
[HttpPost]
public ActionResult Index(SomeViewModel s)
{
return View();
}
and change your view as below
Updated
#model somenamespace.SomeViewModel
#Html.DropDownListFor(m => m.studentname , Model.studentlist , "select student");
i am trying to create user reviews under each product, i used Html.RenderAction
Html.RenderAction("ProductReviewTest", new { id = productids });
it works fine but it takes 9.4s to load the product page with the reviews, so tried Html.RenderPartial but gives error
my product view:
#model MVCProduct.Models.Product
<!--here displaying products-->
<!--displaying reviews in same view-->
<div class="display-field">
<p> Reviews for #Html.DisplayFor(model => model.ProductTitle) </p>
#{
int productid = Model.ProductID;
Html.RenderPartial("ProductReviewTest", new { id = productid });
}
</div>
my review view model:
public class ProductViewModel
{
public int ReviewId { get; set; }
public int? ProductID { get; set; }
public string ReviewTitle { get; set; }
public string ReviewMessage { get; set; }
public int? Rating { get; set; }
public string CustomerName { get; set; }
public string ReviewStatus { get; set; }
}
my ViewResult:
public PartialViewResult ProductReviewTest(int id)
{
List<ProductViewModel> productviewmodel = (from a in dbo.ProductReviews
where a.ProductID ==id
select new ProductViewModel
{
ReviewId=a.ReviewId,
ProductID=a.ProductID,
ReviewTitle =a.ReviewTitle,
ReviewMessage =a.ReviewMessage,
Rating =a.Rating,
CustomerName =a.CustomerName,
ReviewStatus=a.ReviewStatus
}).ToList();
return PartialView(productviewmodel);
}
my review view:
#model IEnumerable<MVCProduct.Models.ProductViewModel>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.ReviewId)
</th>
.......
</table>
error:
The model item passed into the dictionary is of type
'<>f__AnonymousType51[System.Int32]', but this dictionary requires a
model item of type
'System.Collections.Generic.IEnumerable1[Review.Models.ProductViewModel]'.
any help would be great.
There is a difference between RenderAction and RenderPartial. In the first you are calling action, but in second, you are directly calling partial view.
So you cannot pass productId in RenderPartial, instead you need to pass List<ProductViewModel>. Also in RenderPartial, you need to give partial view name, not the action name.
ViewResult:
public PartialViewResult ProductReviewTest()
{
return PartialView();
}
product view:
#model MVCProduct.Models.Product
<!--here displaying products-->
<!--displaying reviews in same view-->
<div class="display-field">
<p> Reviews for #Html.DisplayFor(model => model.ProductTitle) </p>
#{
int productid = Model.ProductID;
Html.RenderPartial("ProductReviewTest", Model.ProductReviews });
}
</div>
you are returning a List of ProductViewModel to view.
Instead use
var productviewmodel = (from a in dbo.ProductReviews
where a.ProductID ==id
select new ProductViewModel
{
ReviewId=a.ReviewId,
ProductID=a.ProductID,
ReviewTitle =a.ReviewTitle,
ReviewMessage =a.ReviewMessage,
Rating =a.Rating,
CustomerName =a.CustomerName,
ReviewStatus=a.ReviewStatus
}).FirstOrDefault();
return PartialView(productviewmodel);
I initially set up my dropdown with submit button which was fine but now I wanted to have it just work without the button (I added onchange). However now I find another difficulty that initially when page is displayed, if I "select" the first option, nothing happens (obviously) so I though to add "please select" option. I found couple of solutions such as writing my custom list of SelectListOptions but this seems like it could be over the top for my case. Could anyone shed some light here and let me know what would be the easiest option here? Sorry if it is simple answer I am really stuck. Here is my code:
Model
public class SurveyDropdownModel
{
public SelectList selectSurveys { get; set; }
public string selectedId { get; set; }
public IEnumerable<RespondentModel> respondents { get; set; }
public SurveyDropdownModel(List<SurveyModel> surveys)
{
selectSurveys = new SelectList(surveys, "SurveyID", "SurveyTitle");
respondents = null;
}
}
public class SurveyModel
{
[Required]
[Display(Name = "Survey ID")]
public int SurveyID { get; set; }
[Display(Name = "Title")]
public string SurveyTitle { get; set; }
[Display(Name = "Updated")]
public DateTime SurveyUpdatedDate { get; set; }
[Display(Name = "Active")]
bool IsActive { get; set; }
}
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
HealthCheckDataLayer.HealthCheckRepository repo = new HealthCheckRepository(connectionString);
List<SurveyModel> surveyList = repo.ReturnSurveys<SurveyModel>();
var model = new SurveyDropdownModel(surveyList);
return View(model);
}
[HttpPost]
public ActionResult Index(SurveyDropdownModel model)
{
//not important here
}
}
View
#model HealthCheckWebApp.Models.SurveyDropdownModel
#{
ViewBag.Title = "Home Page";
}
<div class="row">
<div class="col-md-4">
<h4>Select product:</h4>
#using (Html.BeginForm("Index", "Home"))
{
#Html.DropDownList("selectedId", Model.selectSurveys, new { onchange = "this.form.submit()" })
}
</div>
</div>
<br />
<br />
#if(Model.respondents!=null)
{
#* not relevant here*#
}
I guess now that I didn't include how do I pull my list , I am calling a stored procedure from my repository there (It's required to do it with SP).
Thanks.
Use #Html.DropDownListFor. Here is a description.
Usage:
#Html.DropDownListFor(x=> x.selectedId, Model.selectSurveys, "Select something", new { onchange = "this.form.submit()" )
I am trying to use Html.DropDownListFor to build a dropdown list and get the user selected value. I can get the list to display but cannot figure out how to get the link to pass the selected value.
I have the following model:
public partial class ProductVariant
{
public int ID { get; set; }
public string Sku { get; set; }
}
The following ViewModel:
public class SkuToDiscountViewModel
{
public int ID { get; set; }
public string Sku { get; set; }
public IEnumerable<ProductVariant> Products { get; set; }
}
The following Controller action:
public ViewResult Index()
{
SkuToDiscountViewModel sModel = new SkuToDiscountViewModel();
List<ProductVariant> prodSkus = db.ProductVariants.ToList();
sModel.Products = prodSkus;
return View(sModel);
}
The following view:
#model mySpace.ViewModel.SkuToDiscountViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using(Html.BeginForm())
{
Html.DropDownListFor(x=>x.ID,
new SelectList(Model.Products,"ID", "Sku", Model.ID), " select ")
<p>
#Html.ActionLink("Edit", "Edit")
</p>
}
Any help is appreciated.
You need to a submit button to your form:
#model mySpace.ViewModel.SkuToDiscountViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using(Html.BeginForm())
{
Html.DropDownListFor(x=>x.ID,
new SelectList(Model.Products,"ID", "Sku", Model.ID), " select ")
<p>
<input type="submit" value="Save" />
</p>
}
Then you need to add an Action to your controller like this:
[HttpPost]
public ActionResult Index(SkuToDiscountViewModel postedModel)
{
// postedModel.ID will contain the value selected in the drop down list
}
I am new to MVC and am trying to populate a DropDownList in my view with a list of 'rules' from my controller. When I do it the way listed, I just get a dropdownlist with a bunch of items that say CellularAutomata.Models.Rules. I know I am doing this incorrectly, I'm just wondering how I actually get it to show the rule description for each rule in the dropdownlist.
I have a Model
public class Rule
{
public int ID { get; set; }
public int Name { get; set; }
public string Description{ get; set; }
public Rule(int name, string description)
{
Name = name;
Description = description;
}
public Rule()
{
Name = 0;
Description = "";
}
}
A Controller
public ActionResult Index()
{
var rules = from rule in db.Rules
select rule;
return View(rules.ToList());
}
And a view
#model IEnumerable<CellularAutomata.Models.Rule>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<td>
#Html.DropDownList("Test", new SelectList(Model))
</td>
</tr>
</table>
You could have a view model:
public class MyViewModel
{
public string SelectedRuleId { get; set; }
public IEnumerable<Rule> Rules { get; set; }
}
and then in your controller:
public ActionResult Index()
{
var model = new MyViewModel
{
Rules = db.Rules
};
return View(model);
}
and in the view:
#model CellularAutomata.Models.MyViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DropDownListFor(
x => x.SelectedRuleId,
new SelectList(Model.Rules, "ID", "Description")
)