Dropdown Mvc Display Default Selected Item - asp.net-mvc

I am new in MVC, I would like to ask if you can teach me how to set/display the default item in the dropdown list?
in the Controller..
[HttpGet]
public ActionResult Edit(int ID)
{
EmployeeDBEntities o = new EmployeeDBEntities();
Employee e = new Employee();
e = o.Employees.Single(x => x.EMP_ID == ID);
ViewBag.Dept = o.uspDeptCbo().Select(x => new SelectListItem { Value = x.DEPT_ID.ToString() , Text=x.DEPARTMENT });
return View(e);
}
View
<div class="editor-field">
#Html.DropDownList("Dept",string.Empty)
#Html.ValidationMessageFor(model => model.DEPT_ID)
</div>

i got it!
in the controller..
enter code here
[HttpGet]
public ActionResult Edit(int ID)
{
ViewBag.Dept = o.uspDeptCbo().Select(x => new SelectListItem { Text = x.DEPARTMENT, Value = x.DEPT_ID.ToString(), Selected = (x.DEPT_ID.ToString() == "3") });
}
in the view..
<fieldset>
#Html.DropDownList("Dept", string.Empty)
</fieldset>
Thank you.

Related

BeginForm not showing initial Dropdown List Value

I am using BeginForm and the initial value of one of the Dropdown's is not being set properly. The value is held in a SelectLitemItem and is correctly shown in the preceding Table (in the Index view). The available values provided for list are also correct. It always defaults to "Create" which has a value of "1" even when it should be "Update" which has a value of "2".
The Model.RuleType.Value is shown correctly if I just display it on the form.
I cannot see what I'm doing wrong. I can see no duplicate ID/ Name and have tried including a Hidden field.
There is another dropdown that happens to use a common value for both Value and Text and that works.
Any ideas?
Thanks.
#model AMS.Web.Areas.Admin.Models.RuleActionModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true) #Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.RuleType, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.Partial("Partials/_RuleTypeDropdown") #Html.ValidationMessageFor(model => model.RuleType)
</div>
</div>
RuleTypeDropdown
#using Kendo.Mvc.UI;
#(Html.Kendo().DropDownList()
.Name("RuleType")
.DataTextField("Text")
.DataValueField("Value")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("RuleTypeList", "List", new { Area = "Admin" });
});
})
)
Model
public class RuleActionModel
{
public RuleActionModel() { }
public RuleActionModel(RuleAction ruleAction)
{
...
RuleType = new SelectListItem()
{
Value = ruleAction.RuleType.ToString(),
Text = ((RuleType)(ruleAction.RuleType)).EnumToString()
};
}
[Display(Name = "Type")]
public SelectListItem RuleType { get; set; }
Controller
public ActionResult Edit(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
RuleAction ruleAction = UnitOfWork.RuleActionRepository.FirstOrDefault(x => x.ID == id);
if (ruleAction == null)
{
return HttpNotFound();
}
var model = new RuleActionModel(ruleAction);
return View(model);
}

How do i get the value from my drop down list

I am trying to return the selected item and when i debug my code, the view data track list is always null.
How can I assign the value to the view data?
public ActionResult EditParcel(int id)
{
Parcel parc = _abcSearchService.GetAbcParcel(id);
List<SelectListItem> TrackList = new List<SelectListItem>
{
new SelectListItem { Text = "Processing", Value = "Processing", Selected = true},
new SelectListItem { Text = "Out for delivery", Value = "Out for delivery"},
new SelectListItem { Text = "Delivered", Value = "Delivered"},
};
ViewData["TrackList"] = TrackList;
[HttpPost]
public ActionResult EditParcel(Parcel parcel)
{
try
{
var TrackingStatus = ViewData["TrackList"];
parcel.Tracking_Status = (string)TrackingStatus;
_abcSearchService.UpdateParcelDetails(parcel);
return RedirectToAction("Parcel", new { id = parcel.ParcelID, Controller = "ABCParcel" });
}
catch
{
return View();
}
}
The drop down list appears on my edit action result, when i select an item from the drop down list to update the item the http post action result happens, the view data TrackList is null.
This is my view
 <div class="editor-label">
<%: Html.LabelFor(model => model.Tracking_Status) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("TrackList", (List<SelectListItem>)ViewData["TrackList"])%>
<%--<%: Html.EditorFor(model => model.Tracking_Status) %>--%>
<%: Html.ValidationMessageFor(model => model.Tracking_Status) %>
Use following line instead to get the selected value from drop down in your POST action.
var TrackingStatus = Request["TrackList"];

DropdownList With Data Entity Framework

This is my DropdownList :
<div class="editor-label">
<p>
<%: Html.LabelFor(model => model.Gov) %>
</p>
</div>
<div class="editor-field">
<p>
<%=Html.DropDownListFor(model => model.Gov, ViewBag.gov as SelectList)%>
<%: Html.ValidationMessageFor(model => model.Gov) %>
</p>
and this is my view controller :
public ActionResult TestR()
{
ViewBag.gov = new SelectList(entity.gouvernerat, "Idgov", "Nomg");
return View();
}
With HttpPost :
[HttpPost]
public ActionResult TestR(LogModel.preRegister Model)
{
if (ModelState.IsValid)
{
if (LogModel.preRegister.Verifuser(Model.IDag))
{
ModelState.AddModelError("", "Agence existe deja");
return View(Model);
}
else
{
int ins = LogModel.preRegister.Register(Model);
if (ins > 0)
{
return View("Index");
}
else return View();
}
}
else
{
return View();
}
}
Now Dropdown list show me the list of Gov in my DB(that's what i want), but when i clic on create i got this error in my DropdownLisrt There is no ViewData item of type 'IEnumerable <SelectListItem>' with key 'Gov'.
This is pretty easy with LINQ to SQL. Let's say you have a table Govs that contains your "Tunis", "Ariana", etc. strings. You can then create your select list like this:
govs.Select( x => new SelectListItem { Text = x.Name, Value = x.Name } );
Of course you can even be more flexible and assign the value to something else, like an ID.
Update: more details to answer questions posed in comments:
Add the select list items in the view model:
public IEnumerable<SelectListItem> GovItems { get; set; }
Then, in the controller, before returning your view:
// database code to get "Govs" table goes here....
var vm = new MyViewModel {
GovItems = govs.Select( x => new SelectListItem { Text = x.Name, Value = x.Name } );
}
Then in your view:
#Html.DropDownListFor( x => x.Gov, Model.Govs )
I hope this helps. If you're still confused, I recommend reading some tutorials about ASP.NET MVC. I recommend Microsoft's official one:
http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part1-cs

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>

How to make dropdownlist show a selected value in asp.net mvc?

I have an edit page with a Html.DropDownList in it....I cant show the dropdownlist value it always shows up with Select instead i want to make the dropdown show an item as selected based on a model value say Model.Mes_Id... Any suggestion how it can be done...
<p>
<label for="MeasurementTypeId">MeasurementType:</label>
<%= Html.DropDownList("MeasurementType", // what should i give here?)%>
<%= Html.ValidationMessage("MeasurementTypeId", "*") %>
</p>
EDIT: It has the list items but i want to show a value selected in the edit view...
public ActionResult Edit(int id)
{
var mesurementTypes = consRepository.FindAllMeasurements();
ViewData["MeasurementType"] = mesurementTypes;
var material = consRepository.GetMaterial(id);
return View("Edit", material);
}
My repository method,
public IEnumerable<SelectListItem> FindAllMeasurements()
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name
};
return mesurements;
}
Set the selected item when you create the IEnumerable<SelectListItem>.
Personally I would create a specialized viewmodel for the form but going by your code, do something like:
public ActionResult Edit(int id)
{
//Put this first
var material = consRepository.GetMaterial(id);
//pass in your selected item
var mesurementTypes = consRepository.FindAllMeasurements(material.MeasurementTypeId);
ViewData["MeasurementType"] = mesurementTypes;
return View("Edit", material);
}
Then change your repository method to something like:
public IEnumerable<SelectListItem> FindAllMeasurements(int selectedId)
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name,
Selected = mt.Id == selectedId
};
return mesurements;
}
HTHs,
Charles
Have a look at this blog entry.
http://weblogs.asp.net/ashicmahtab/archive/2009/03/27/asp-net-mvc-html-dropdownlist-and-selected-value.aspx
Basically, you need to convert your mesurementTypes list/enumerable into a SelectList or IEnumerable<SelectListItem>.
I would recommend, if possible, upgrading to ASP.NET MVC2 and using Html.DropDownListFor()
You should be returning a SelectionList which can specify a selected item.
How to create a DropDownList with ASP.NET MVC
Assuming that Model.Mes_Id contais the selected value, you can do something like this
<%
var Measurements = new SelectList((IEnumerable)ViewData["MeasurementType"], "Id", "Name", Model.Mes_Id);
Response.Write(Html.DropDownList("measurement_type", Measurements, "Select"));
%>
Html.DropDownListFor didn't work for me So I got the poppy like this
(in Edit method )
CreatList(long.Parse(wc.ParentID.ToString()));
private void CreatList(long selected= 0)
{
SqlConnection conn = new SqlConnection(Config.ConnectionStringSimple);
conn.Open();
Category wn = new Category(conn);
CategoryCollection coll = new CategoryCollection();
Category.FetchList(conn, ref coll);
ViewBag.ParentID = GetList(coll, selected);
}
private List<SelectListItem> GetList(CategoryCollection coll, long selected)
{
List<SelectListItem> st = new List<SelectListItem>();
foreach (var cat in coll)
{
st.Add( new SelectListItem
{
Text = cat.Name,
Value = cat.ID.ToString(),
Selected = cat.ID == selected
});
}
SelectListItem s = new SelectListItem {
Text = Resources.lblSelect,
Value = "0"
};
st.Insert(0, s);
return st;
}
<div class="editor-label">
#Html.LabelFor(model => model.ParentID)
</div>
<div class="editor-field">
#Html.DropDownList("ddlCat", (List<SelectListItem>)ViewBag.ParentID)
#Html.ValidationMessageFor(model => model.ParentID)
</div>

Resources