dropdown load on selection of other dropdown - asp.net-mvc

I have the dropdown trigger an ajax post that sends the selected value of country dropdown .
model class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_4___A_Registration_Form.Models
{
public class ModelServices
{
private readonly MyCompanyEntities entities = new MyCompanyEntities();
public IEnumerable<Country> GetCountryList()
{
return entities.Countries.ToList();
}
public IEnumerable<countryState> GetStateByCountry(int CountryID)
{
return entities.countryStates.Where(s => s.CountryId == CountryID).ToList();
}
public IList<EmployeeRegInfo> GetAllEmployeeList()
{
var myQuery = (from e in entities.Employees
join c in entities.Countries on e.Country equals c.CountryId
join s in entities.countryStates on e.State equals s.StateId
select new EmployeeRegInfo()
{
Id = e.Id,
Emp_ID = e.Emp_ID,
Dept = e.Dept,
Name = e.Name,
CountryName = c.County,
StateName = s.State,
City = e.City,
Mobile = e.Mobile
});
return myQuery.ToList();
}
public bool IsEmpAlreadyExist(string EMP_CODE)
{
bool IsRecordExist = false;
var result = (from t in entities.Employees
where t.Emp_ID == EMP_CODE
select t).SingleOrDefault();
if (result != null)
{
IsRecordExist = true;
}
return IsRecordExist;
}
public void AddNewEmployee(Employee emp)
{
entities.Employees.Add(emp);
entities.SaveChanges();
}
}
}
create.cshtml
#model MVC_4___A_Registration_Form.Models.EmployeeRegInfo
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#ViewBag.ErrorMsg
<table>
<tr>
<td>
#Html.LabelFor(model => model.Emp_ID)
</td>
<td>#Html.EditorFor(model => model.Emp_ID)
#Html.ValidationMessageFor(model => model.Emp_ID)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Name)
</td>
<td>#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Dept)
</td>
<td>#Html.EditorFor(model => model.Dept)
#Html.ValidationMessageFor(model => model.Dept)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Country)</td>
<td>#Html.DropDownList("Country", ViewBag.Country as SelectList, new { Styles = "width:300px" })</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.State)
</td>
<td>
<select id="State" name="State" style="width: 200px"></select>
#Html.ValidationMessageFor(model => model.State)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.City)</td>
<td>#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Mobile)</td>
<td>#Html.EditorFor(model => model.Mobile)
#Html.ValidationMessageFor(model => model.Mobile)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Add Employee" /></td>
</tr>
</table>
}
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.post(url, { countryID: countryID }, function (data) {
$("#State").empty();
var items;
$.each(data, function (i, states) {
items += "<option value=" + states.StateId + ">" + states.State + "</option>";
});
$("#State").html(items);
});
});
});
</script>
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_4___A_Registration_Form.Models;
namespace MVC_4___A_Registration_Form.Controllers
{
public class ManageEmployeeController : Controller
{
ModelServices model = new ModelServices();
//
// GET: /ManageEmployee/
public ActionResult Index()
{
IList<EmployeeRegInfo> empList = new List<EmployeeRegInfo>();
empList = model.GetAllEmployeeList();
return View(empList);
}
public ActionResult Create()
{
IEnumerable<Country> country;
country = model.GetCountryList();
ViewBag.Country = new SelectList(country, "CountryId", "County", "CountryId");
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
bool checkEmpCodeExist = false;
checkEmpCodeExist = model.IsEmpAlreadyExist(collection["Emp_ID"]);
if (!checkEmpCodeExist)
{
try
{
Employee emp = new Employee();
emp.Emp_ID = collection["Emp_ID"];
emp.Name = collection["Name"];
emp.Dept = collection["Dept"];
emp.Country = Convert.ToInt32(collection["Country"]);
emp.State = Convert.ToInt32(collection["State"]);
emp.City = collection["City"];
emp.Mobile = collection["Mobile"];
model.AddNewEmployee(emp);
return RedirectToAction("Index");
}
catch (Exception ex)
{
return RedirectToAction("Create");
}
}
else
{
ViewBag.ErrorMsg = "Employee Code Already Exist";
return RedirectToAction("Create");
}
}
public JsonResult GetStatesByCountry(int id)
{
var states = model.GetStateByCountry(id);
return Json(states, JsonRequestBehavior.AllowGet);
}
}
}
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.

Hey I got the answer
some change in ajax code and controller
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.ajax({
url: url,
data: { id: countryID },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#State").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
[HttpPost]
public JsonResult GetStatesByCountry(string id)
{
int ids = Convert.ToInt32(id);
var states = model.GetStateByCountry(ids);
SelectList obgcity = new SelectList(states, "StateId", "State", 0);
return Json(obgcity);
}

Related

Infinite Scroll - ASP.NET Core MVC

We are trying to implement infinite scroll in data grid in an ASP.NET Core MVC application. Searched a lot but could not find a good solution. Has any one used infinite scroll in data grid in an ASP.NET Core MVC . If so can you provide any guidance
I faced the same problem. Here is my solution. It works on nearly any table:
InfinityScroll.js
function InfinitiySroll(iTable, iAction, iParams) {
this.table = iTable; // Reference to the table where data should be added
this.action = iAction; // Name of the conrtoller action
this.params = iParams; // Additional parameters to pass to the controller
this.loading = false; // true if asynchronous loading is in process
this.AddTableLines = function (firstItem) {
this.loading = true;
this.params.firstItem = firstItem;
// $("#footer").css("display", "block"); // show loading info
$.ajax({
type: 'POST',
url: self.action,
data: self.params,
dataType: "html"
})
.done(function (result) {
if (result) {
$("#" + self.table).append(result);
self.loading = false;
}
})
.fail(function (xhr, ajaxOptions, thrownError) {
console.log("Error in AddTableLines:", thrownError);
})
.always(function () {
// $("#footer").css("display", "none"); // hide loading info
});
}
var self = this;
window.onscroll = function (ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
//User is currently at the bottom of the page
if (!self.loading) {
var itemCount = $('#' + self.table + ' tr').length - 1;
self.AddTableLines(itemCount);
}
}
};
this.AddTableLines(0);
}
Here a from Visual Studio scaffold view - a little bit modified
TestData.cshtml
#model IEnumerable<Infinity_Scroll.Models.TestData>
#{
ViewData["Title"] = "TestData";
}
<h1>TestData</h1>
<table id="anyTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Field1)
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section Scripts {
<script src="~/js/InfinitiySroll.js"></script>
<script>
var infinityScroll = new InfinitiySroll("anyTable", "/home/_TestData", { sortOrder: "ascending", searchString: "3" });
</script>
}
The generating of the table rows is moved into a PartialView:
_TestData.cshtml
#model IEnumerable<Infinity_Scroll.Models.TestData>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Field1)
</td>
</tr>
}
And here is the Controller part:
...
private const int BATCH_SIZE = 50;
public IActionResult TestData()
{
return View();
}
[HttpPost]
public IActionResult _TestData(string sortOrder, string searchString, int firstItem = 0)
{
List<TestData> testData = new List<TestData>();
// Generate test data
for (int i = 1; i < 500; i++)
{
testData.Add(new TestData() { Id = i, Field1 = "This is row " + i.ToString() });
}
// Sort and filter test data
IEnumerable<TestData> query;
if (sortOrder.ToLower() == "descending")
{
query = testData.OrderByDescending(m => m.Field1);
}
else
{
query = testData.OrderBy(m => m.Field1);
}
if (!String.IsNullOrEmpty(searchString)) query = query.Where(m => m.Field1.Contains(searchString));
// Extract a portion of data
var model = query.Skip(firstItem).Take(BATCH_SIZE).ToList();
if (model.Count() == 0) return StatusCode(204); // 204 := "No Content"
return PartialView(model);
}
The model:
TestData.cs
namespace Infinity_Scroll.Models
{
public class TestData
{
public int Id { get; set; }
public string Field1 { get; set; }
}
}
You can download a simple Visual Studio example here: https://github.com/ThomasBrockmann/InfinityScroll

ASP.NET MVC pagedlist loose checkboxlist filter

I'm working on an Asp MVC application that contains a grid of data that I can filter with a checkboxlist.I'm using PagedList to display the data. My filter works well on the first page, but if I click on the 2nd page, the filter is cancelled. I don't have this problem with filter using dropdownlist(it's not in the following example).
My view looks like this:
<div class="wrapper">
<nav id="sidebar">
#using (Html.BeginForm("Index", "Missions", FormMethod.Get))
{
#Html.EditorFor(x => x.Decision)
}
</nav>
<div id="content" class="container">
<table class="table table-bordered">
<tr>
<th class="col-md-2">
Decision
</th>
</tr>
#foreach (var item in Model.OnePageOfMissions)
{
<tr>
<td class="col-md-1">
#Html.DisplayFor(modelItem => item.decision)
</td>
</tr>
}
#Html.PagedListPager((IPagedList)Model.OnePageOfMissions, page => Url.Action("Index", new { page, Decision = Model.Decision}))
</table>
</div>
I created a template to display checkboxlist like this:
<div class="form-check row">
#Html.HiddenFor(x => x.ID)
#Html.CheckBoxFor(x => x.IsChecked, htmlAttributes: new { onchange = "form.submit();", #class = "form-check-input col-md-2" })
#Html.LabelFor(x => x.Display, Model.Display, htmlAttributes: new { #class = "form-check-label col-md-8" })
My controller looks like this:
public ActionResult Index(int? page, List<CheckBoxListItem> Decision)
{
IndexViewModel model = new IndexViewModel();
//Display Missions
model.missionsList = db.missions_supportmission.ToList();
//Retrieve parameters
model.Decision = Decision;
//PagedList
var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
var onePageOfMissions = model.missionsList.ToPagedList(pageNumber, 10); // will only contain 10 products max because of the pageSize(equel to 10)
model.OnePageOfMissions = onePageOfMissions;
//Filter
if (model.Decision != null)
{
var selecteddecision = model.Decision.Where(x => x.IsChecked).Select(x => x.ID);
model.OnePageOfMissions = (from m in db.missions_supportmission
join l in db.list_decision
on m.decision equals l.decision_id
where selecteddecision.Contains(l.decision_id)
select m)
.OrderBy(a => a.id)
.ToPagedList(pageNumber, 10);
}
}
}
//Display CheckBox
//Checkboxlist (!important => mettre ce bloc de code après la requête link qui permet de filtrer sur les checkbox)
var allDecisions = db.list_decision.ToList();//returns List<list_decision>
var checkBoxListItems = new List<CheckBoxListItem>(); //nouvelle instance de la classe checkboxlist
model.Decision = checkBoxListItems;
foreach (var decison in allDecisions)
{//On assigne les valeurs "id", "display" et "is checked" à la variable checkboxlistitem
checkBoxListItems.Add(new CheckBoxListItem()
{
ID = decison.decision_id,
Display = decison.name_en,
IsChecked = false //On the add view, no decision are selected by default
});
}
return View(model);
}
I have also a ViewModel:
namespace MissionsDF.Models
{
public class IndexViewModel
{
public IEnumerable<missions_supportmission> missionsList { get; set; }
public List<CheckBoxListItem> Decision { get; set; }
public IndexViewModel()
{
this.Decision = new List<CheckBoxListItem>();
}
public IPagedList<missions_supportmission> OnePageOfMissions { get; set; }
}
}

How to display two views using two different models on the same web page in ASP.NET MVC

Here is the code for controllers and view. I want to display the both views on the same webpage in ASP.NET MVC. How to achieve this goal?
Controller:
public ActionResult LetterList()
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return View(obj);
}
public ActionResult Showimage(string ListId)
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return View(letterList);
}
View Of LetterList
#model LetterPage.Models.ModelView
<div>
#{
foreach (var item in Model.letterDetail)
{
<div>
#item.ListName
</div>
}
}
</div>
ShowImage view:
#model IList< LetterPage.Models.hurf_e_tahaji>
#{
ViewBag.Title = "ShowImage";
}
<table class="table">
<tr>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<img src="#Url.Content("item.Letter_Pic") "/>
</td>
</tr>
}
</table>
When I created these views as partial views and render them into another view exception occurs on the Foreach loop at model.
You can use PartialView:
[HttpPost]
public PartialViewResult LetterList()
{
if (Request.IsAjaxRequest())
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return PartialView(obj);
}
return null;
}
[HttpPost]
public PartialViewResult Showimage(string ListId)
{
if (Request.IsAjaxRequest())
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return PartialView(letterList);
}
return null;
}
Then you have to define your partial views (like code you posted), And inside the main view:
<div class="LetterList">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
<div class="Showimage">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$.post('/Home/LetterList', function(data) {
$('.LetterList').html(data);
});
$.post('/Home/Showimage/' + ListId, function(data) {
$('.Showimage').html(data);
});
});
</script>
}

How to create view for given model

I am new to asp .net mvc 4.0. i have given model. i am not getting how can i create view for model. I am facing problem at IList JournalEntries. other entry i am able to do.
public class Journal : BaseClass
{
public virtual string VoucherNo { get; set; }
public virtual DateTime VoucherDate { get; set; }
public string VoucherDateView {
get
{
return VoucherDate.ToShortDateString();
}
}
public IList<JournalEntry> JournalEntries { get; set; }
public IList<Ledger> Accounts { get; set; }
public double TotalAmount
{
get
{
double sum = 0;
if (JournalEntries != null && JournalEntries.Count>0)
foreach (var journal in JournalEntries)
sum = journal.Principal + journal.Interest+sum;
return sum;
}
}
}
I have tried below view but add entry doesn't works.
#model Sms.CoreSociety.Journal
#{
ViewBag.Title = "Create";
}
#{
string data = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);
}
<script type="text/javascript">
$(document).ready(function () {
$('#document').validate();
$("#VoucherDate").mask("99/99/9999", { placeholder: " " });
function entryVm(entries) {
var self = this;
self.entryList = ko.observableArray(entries);
self.entry = ko.observable();
self.rowClick = function(entry1) {
alert("Delete alert");
self.dispatchList.remove(entry1);
};
self.addEntry = function() {
alert("Add alert");
this.entryList.push({ AccountName_AccountHead: "", DebitCredit: "", Principal: "0.0", Interest: "0.0", Narration: ""});
};
}
var models = #Html.Raw(Json.Encode(Model.JournalEntries)) ;
ko.applyBindings(new entryVm(models));
});
</script>
#using (Html.BeginForm(null, null, FormMethod.Post, new Dictionary<string, object>() { { "class", "form-horizontal" }, { "id", "document" } }))
{
#Html.ValidationSummary(true)
<fieldset>
<div class="row">
<div class="span1">
<label>Voucher No</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.VoucherNo)
</div>
</div>
<div class="row">
<div class="span1">
<label>Voucher Date</label>
</div>
<div class="span5">
#Html.TextBoxFor(model => model.VoucherDate, "{0:dd/MM/yyyy}", new Dictionary<string, object>() { { "class", "required" } })
</div>
</div>
<div class="row">
<div class="span1">
<label>Amount</label>
</div>
<div class="span5">
#Html.DisplayFor(model => model.TotalAmount)
</div>
</div>
<input type="submit" value="Save" class="btn" id="submit"/>
#if (Model.Id != new Guid())
{
<div style="float: right">
<a class="btn btn-danger" href='#Url.Action("Delete")/#Model.Id' aria-hidden="true">Delete</a>
</div>
}
</fieldset>
}
<h4>Journal Entry</h4>
<p >Entry for<span data-bind="text: entryList().length"> </span> entry(s)</p>
<button data-bind="click: addEntry" class="btn">Add Record</button>
<table>
<tbody data-bind="template: { name: 'entryRowTemplate', foreach: entryList }"></tbody>
</table>
<script type="text/html" id="entryRowTemplate">
<tr>
<td>AccountName_AccountHead: \$ <input data-bind="value: AccountName.AccountHead"/> </td>
<td>DebitCredit: \$ <input data-bind="value: DebitCredit"/></td>
<td>Principal: \$ <input data-bind="value: Principal"/></td>
<td>Interest: \$ <input data-bind="value: Interest"/></td>
<td>Narration: \$ <input data-bind="value: Narration"/></td>
<td>Delete</td>
</tr>
</script>
below is my Journal controller
using System;
using System.Linq;
using System.Web.Mvc;
using Sms.CoreSociety;
using System.Collections.Generic;
namespace SmsModernUI.Controllers
{
public class JournalController : BaseController
{
//
// GET: /AccountGroup/
public ActionResult Index()
{
var journals = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo);
return View(journals);
}
public ActionResult Create(Guid id)
{
if (id == new Guid())
{
var journal = new Journal();
string lastvoucherno = Repository.GetAll<Journal>().OrderBy(x => x.VoucherNo).Last().VoucherNo;
journal.VoucherNo = (int.Parse(lastvoucherno) + 1).ToString();
journal.VoucherDate = System.DateTime.Now;
journal.JournalEntries = new List<JournalEntry>();
journal.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal);
}
var journal1 = Repository.Get<Journal>(id);
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == id);
journal1.Accounts = Repository.GetAll<Ledger>();
return PartialView(journal1);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Journal journal)
{
if (journal.Id == new Guid())
{
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
else
{
Journal jr = Repository.Get<Journal>(journal.Id);
var entries = Repository.GetAll<JournalEntry>(x=>x.Journal.Id == journal.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var jj = Repository.Save(journal);
foreach (var journalentry in journal.JournalEntries)
{
journalentry.Id = jj.Id;
Repository.Save(journalentry);
}
}
return RedirectToAction("Index");
}
public ActionResult Index1()
{
Journal journal1 = Repository.Get<Journal>(new Guid("7A6EEBBC-2F3A-4A27-ACF8-A1D40115A68F"));
journal1.JournalEntries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == journal1.Id);
journal1.Accounts = Repository.GetAll<Ledger>();
return View(journal1);
}
public ActionResult Delete(Guid id)
{
Journal jr = Repository.Get<Journal>(id);
var entries = Repository.GetAll<JournalEntry>(x => x.Journal.Id == jr.Id);
foreach (var entry in entries)
{
Repository.Delete(entry);
}
var result = Repository.Delete(jr);
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Create1(Journal journal)
{
var temp = journal;
return RedirectToAction("Create",journal.Id);
}
}
}
Views are not genereted from models. You need Controller Action method to pass your model to View.
public ActionResult()
{
var model = new Journal
{
//**define here value of model's properties, that you need in View
}
return View(model);
}
EDITED: After your addition.
I would devide it into two parts. Create ViewModel and pass it from View To Controller.
public JurnalViewModel
{
public Journal journal {get; set;}
public IList<JournalEntry> JournalEntries {get; set;}
}
Than in Create action first create journal and after foreach JournalEntries in model create new JournalEntry.
EDITED 2 To your comment. Quick sample:
[HttpPost]
public ActionResult Create (JurnalViewModel model)
{
var journal = new Journal();
db.Journals.Add(journal);
journal.name = model.journal.name
.....
//**some code
db.SaveChanges()
foreach(var item in model.JournalEntries )
{
var entry = new JournalEntry()
db.JournalEntries .Add(entry);
entry.property = item.property;
....
//**some code
db.SaveChanges()
}
}
Your problem is that you have no class constructor for JournalEntries.
public Journal()
{
JournalEntries = new List<JournalEntry>();
Accounts = new List<Ledger>();
}
Right click to your Action method inside controller and click add view then check create strongly typed-view checkbox then choose your desired model from dropdown in displayed dialogue box

problems with html helper method

I can't figure out how to send a parameter from a dropdownlist to my model. Could someone please show me an example of how to do this?
As always you start by defining a model:
public class MyViewModel
{
public string SelectedValue { get; set; }
public SelectList Items
{
get
{
return new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}, "Value", "Text");
}
}
}
Controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// You will get the selected value inside model.SelectedValue here
// => do something with it
....
}
}
Strongly typed view:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedValue, Model.Items) %>
<input type="submit" value="OK" />
<% } %>
public ActionResult Edit(int id)
{
Affiliate affiliate = affiliateRepository.GetAffiliate(id);
List<SelectListItem> StateList = new List<SelectListItem>();
SelectListItem item;
Dictionary<string, string> dictState = S127Global.Misc.getStates();
foreach (KeyValuePair<string, string> k in dictState)
{
item = new SelectListItem();
item.Text = k.Value;
item.Value = k.Key;
StateList.Add(item);
}
item = new SelectListItem();
item.Text = " - Select State - ";
item.Value = "";
StateList.Insert(0, item);
//create new select list with affiliate.state as the selected value in ViewData
ViewData["State"] = new SelectList(StateList.AsEnumerable(), "Value", "Text",affiliate.State);
return View(affiliate);
}
code for view
<div class="editor-label">
<%: Html.LabelFor(model => model.State) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("State")%>
<%: Html.ValidationMessageFor(model => model.State) %>
</div>

Resources