Reputation: 1267
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);**
}
Upvotes: 0
Views: 6659
Reputation: 5048
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);
Upvotes: 1
Reputation: 1
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");
Upvotes: 0