not working dropdown list in edit view in mvc4 razor - asp.net-mvc-4

am unable to get correct value from drop down in mvc4. my edit view code is
#Html.DropDownList("IDCountry", (IEnumerable<SelectListItem>)ViewBag.IDCountry,
new { #class = "span6" })
if i use below code am able to get correct value but am unable to apply style for dropdownlist
#Html.DropDownList("IDCountry",String.empty)
please solve my problem.

You should not use the same value (IDCountry) as first and second argument for the dropdown. The first argument represents the value to bind the dropdown to while the second represents the available values. So:
#Html.DropDownList(
"SelectedCountryID",
(IEnumerable)ViewBag.IDCountry,
new { #class = "span6" }
)
To avoid all those confusions with Dropdowns I would recommend you using a view model:
public class MyViewModel
{
public string SelectedCountryID { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
}
and then your controller action will populate and pass this view model to the view:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
// preselected an element with Value = "2"
model.SelectedCountryID = "2";
// obviously those values could come from a database or something
model.Countries = new[]
{
new SelectListItem { Value = "1", Text = "Country 1" },
new SelectListItem { Value = "2", Text = "Country 2" },
new SelectListItem { Value = "3", Text = "Country 3" },
new SelectListItem { Value = "4", Text = "Country 4" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content("Thanks for selecting country ID: " + model.SelectedCountryID);
}
}
and finally in your view use the strongly typed helper:
#model MyViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.SelectedCountryID)
#Html.DropDownListFor(
x => x.SelectedCountryID,
Model.Countries,
new { #class = "span6" }
)
</div>
<button type="submit">OK</button>
}
See how the very instant you STOP using ViewBag and remove absolutely all traces from it in your application everything becomes crystal clear?

Related

MVC Razor - How to update a multiple rows in a selected column from a dropdown list SQL

I think the title says it all...
I want to update a whole table with an input filled value into a selected column (selected from a dropdown list) if the value of another column is equal to a selected value (from another dropdown list). Putting all this together seem pretty hard for me...
Like this kind of Query...
var db = Database.Open("DatabaseX");
var updateCommand = "UPDATE TableX Set SelectedColumn(dropdownlistA) = (InputA) IF ColumnX = Selected Values(dropdownlistB)";
Sorry for my english
If you are having trouble getting the selected values from the dropdown on form submit, you may try this.
Create a view model with properties for the data for the dropdown and the selected option value.
public class CreateUserVm
{
public int SelectedCam { set; get; }
public List<SelectListItem> Cams { set; get; }
public int SelectedCat { set; get; }
public List<SelectListItem> Categories { set; get; }
}
And in your GET action, create an object of this, initialize the collection properties and send tot he view.
public ActionResult Create()
{
var v = new CreateUserVm
{
Categories = new List<SelectListItem>
{
new SelectListItem {Value = "1", Text = "Photo"},
new SelectListItem {Value = "2", Text = "Video"}
},
Cams = new List<SelectListItem>
{
new SelectListItem {Value = "25", Text = "DSLR"},
new SelectListItem {Value = "28", Text = "Point and Shoot"}
}
};
return View(v);
}
Now your create view should be strongly typed to this CreateUserVm class.
#model CreateUserVm
#using(Html.BeginForm())
{
#Html.DropDownListFor(g=>g.SelectedCat, Model.Categories)
#Html.DropDownListFor(g=>g.SelectedCam, Model.Cams)
<input type="submit" />
}
And in your HttpPost action method, we will use the CreateUserVm object as the parameter so that the posted model will be mapped to it by the default model binder.
[HttpPost]
public ActionResult Create(CreateUserVm model)
{
var camId = model.SelectedCam;
var catId = model.SelectedCat;
// use camId and catId to update your db.
// to do : Save and Redirect
}

Selected item not showing in dropdown list in Edit Form

Eg: I have both Add form and Edit Form. When I add details in dropdown List it successfully saved in database. When I go for Edit the selected item is not showing in the dropdown list.
Code I used in EditPartial.
#Html.DropDownListFor(m => m.Language_ID,(List<SelectListItem>)ViewBag.LanguageList,null, new { type = "text", Class = "validate[required] form-control smheight", style = " font-size:11px; padding-top:3px" })
Controller code
var _tableLanguage = db.LANGUAGES_TABLE.Select(_Log => new SelectListItem
{
Text = _Log.Languages,
Value = SqlFunctions.StringConvert((decimal)_Log.Language_ID) }
).ToList();
_tableLanguage.Insert(0, new SelectListItem { Text = "Select", Value = "0" });
ViewBag.LanguageList = _tableLanguage;
var items = new SelectList(db.LANGUAGES_TABLE.ToList(), "Language_ID", "lang");
ViewData["Language_ID"] = items;
Model
public partial class LANGUAGE_PROFFICIANCY
{
public int Language_Proficiency_ID { get; set; }
public Nullable<int> Candidate_ID { get; set; }
public Nullable<int> Language_ID { get; set; }
}
Change you controller code to
ViewBag.LanguageList = new SelectList(db.LANGUAGES_TABLE, "Language_ID", "Languages");
and delete the following
var items = new SelectList(db.LANGUAGES_TABLE.ToList(), "Language_ID", "lang");
ViewData["Language_ID"] = items;
and change the view to
#Html.DropDownListFor(m => m.Language_ID, (SelectList)ViewBag.LanguageList, "Select", new {...});
If the value of property Language_ID matches the value of one of your option values, then it will be selected in the view
Note also your html attributes are invalid. type = "text" makes no sense - its a <select> element, not a <input type="text" ..> element. Class = "validate[required] makes no sense either (no sure what you think this would do)

kendo dropdownlist in pop up editor not binding to viewmodel

I have a ViewModel that i use in a grid.
Lets name it DivisionVm
public class DivisionVm {
public int DivisionId
public string Name
public DateTime StartDate { get; set; }
public string Condition
....
}
When I want to update the model I use a custom editor template.Because Condition takes some predefined string values I use a dropdownlist in the template.
#(Html.Kendo().DropDownListFor(model=>model.Condition)
.DataTextField("Text")
.DataValueField("Condition")
.Events(e => e.Change("change"))
.BindTo(new List<ConditionVm>() {
new ConditionVm() {
Text = "Red",
Condition = "Red"
},
new ConditionVm() {
Text = "Green",
Condition = "Green"
},
new ConditionVm() {
Text = "Green",
Condition = "Green"
}
})
)
ConditionVm is just a viewmodel that i use for binding
public class ConditionVm
{
public string Text { get; set; }
public string Condition { get; set; }
}
My problem is that when the pop up editor opens it shows the current condition value in the dropdownlist. But if i select another value from the list, kendo does not track the change.So if i press the update button viemodel does not update.If i change other fields (eg Name) the viemodel is updating but only for these fields.Condition remains the same even if i have selected another value from the dropdown list.
My controller update method is something like this
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DivisionGridUpdate([DataSourceRequest] DataSourceRequest request, DivisionVm division)
{
if (division != null && ModelState.IsValid)
{
......
}
return Json(new[] { division }.ToDataSourceResult(request, ModelState));
}
Have you tried in the grid setting the column of the DDL like a foreing Key?
Like this:
columns.ForeignKey(p => p.yourproperty, (System.Collections.IEnumerable)ViewData["myList"], "Text", "Condition");
Controller (here you fill the list wich will be fill the Dropdownlist:
ViewData["myList"] = myList.Select(e => new
{
Text= e.Text,
Condition= e.Condition
});
And in the pop up editor you just simple:
#Html.EditorFor(model=>model.yourproperty)

ASP.NET MVC 4 Not populating dropdownlist from database

I am new in ASP.NET MVC 4. I want to populate dropdownlist by taking values from database. But dropdownlist doesn't populating with data. I am not getting where I am wrong. On the basis of following link I have develop my code. Is anybody have any other better way so kindly suggest. I am using code first approach with Razor engine.
Click here
My Controller class :
public class iRegController : Controller
{
private iRegDBContext l_oDbBO = new iRegDBContext();
// GET: /iReg/
public ActionResult PopulatejQgrid()
{
var BOList = l_oDbBO
.BO
.ToList()
.Select(d => new SelectListItem
{
Value = d.Id.ToString(),
Text = d.Name + "[ " + d.Code + " ]"
});
ViewBag.BOData = new SelectList(BOList, "Value", "Text");
return View();
}
}
My Model class :
public class BO
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class iRegDBContext : DbContext
{
public DbSet<BO> BO { get; set; }
}
My cshtml class :
#model MvciReg.Models.BO
#{
ViewBag.Title = "PopulatejQgrid";
}
#using (Html.BeginForm())
{
<fieldset>
BO :
#Html.DropDownList("BOData")
<p>
<input type="submit" value="Go" />
</p>
</fieldset>
}
Updated : My table name is BO and Database name is iReg. And my connectionstring is
<add name="iRegDBContext"
connectionString="Data Source=****;Initial Catalog=iReg;User ID=**;Password=****;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
Try to pass your list as a model to Html.DropDownList like this:
#Html.DropDownList("BOData", (SelectList)ViewBag.BOData)
According to msdn
#Html.DropDownList element expect a collection of type IEnumerable to populate the DropDownList. So rewriting your query such as:
IEnumerable<SelectListItem> BOList = l_oDbBO
.BO.Select(d => d)
.AsEnumerable)
.Select(d => new SelectListItem
{
Value = d.Id.ToString(),
Text = d.Name + "[ " + d.Code + " ]"
});
should do the work.
You may try another way:
public ActionResult PopulatejQgrid()
{
var myList = new List<SelectListItems>();
var list = l_oDbBO.BO.ToList();
var items = from g in list
select new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name + "[ " + g.Code + " ]"
};
foreach(var item in items)
myList.add(item);
ViewBag.BOData = myList ;
return View();
}
In you View:
#Html.DropDownList("Booo", (List<SelectListItem>)ViewBag.BOData)
public ActionResult PopulateJQgrid()
{
ViewBag.BOData = new SelectList(l_oDbBO.BO, "Name", "Name");
return View();
}
In your View:
#Html.DropDownList("BOData")
-- SelectList(Context.Table, "the ColumnName of the attribute that you used as value", "the ColumnName of the attribute that you used as the text of your dropdownlist")
:)

Drop Down List Value not passing to controller

This question should be very simple.. I am trying to pass values in my drop down list in my view to the controller.. I'm not getting errors but it's sending a null value for that property. Please help..
My code is as follows:
Controller:
public ActionResult Create()
{
var list = new []
{
new Room{ RoomID = 1, Building = "FAYARD HALL"},
new Room{ RoomID = 2, Building = "WHATEVER HALL"},
new Room{ RoomID = 3, Building = "TIME SQUARE"},
new Room{ RoomID = 4, Building = "MISSISSIPPI"},
new Room{ RoomID = 5, Building = "NEW YORK"},
};
var selectList = new SelectList(list,"RoomID", "Building");
ViewData["BuildingList"] = selectList;
return View();
}
//
// POST: /Room/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Room room)
{
if (ModelState.IsValid)
{
db.Rooms.Add(room);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(room);
}
MY VIEW:
<div>
#Html.LabelFor(model => model.Building, "Building")
</div>
<div>
#Html.DropDownList("BuildingList", String.Empty)
#Html.ValidationMessageFor(model => model.Building)
</div>
Please help...
Thank you.
Is your drop down populated? Given your code I think you need the following to do so:
#Html.DropDownListFor(model => model.Building, ViewData["BuildingList"])
ie. bind the selected value to the Building property of your Room and use the drop down list from your view model to populate the list.
I'm also not sure this is what your intention is. It seems a bit fishy that you are populating a drop down list with rooms and then based on the selection you are creating a new room.
Edit
Ok I'm going to make things a lot easier for you.
I'll start with your classes. Here is the room I am assuming you're working with:
public class Room
{
public int RoomId { get; set; }
public string Building { get; set; }
}
Now let's do something a bit better than using ViewData. I've created a view model for you. You will populate this with your select list and the item you choose in the view will be bound into the SelectedRoomId when you post the form.
public class ViewModel
{
public int SelectedRoomId { get; set; }
public SelectList RoomOptions { get; set; }
}
Controller
private SelectList GetSelectList()
{
var list = new[]
{
new Room { RoomId = 1, Building = "FAYARD HALL"},
new Room { RoomId = 2, Building = "WHATEVER HALL"},
new Room { RoomId = 3, Building = "TIME SQUARE"},
new Room { RoomId = 4, Building = "MISSISSIPPI"},
new Room { RoomId = 5, Building = "NEW YORK"}
};
return new SelectList(list, "RoomId", "Building");
}
public ActionResult Create()
{
ViewModel viewModel = new ViewModel
{
RoomOptions = GetSelectList()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(ViewModel viewModel)
{
if (ModelState.IsValid)
{
// Save here
// create a new room using the SelectedOptionId in the viewModel
return RedirectToAction("Index", "Home");
}
// repopulate the list if something failed
viewModel.RoomOptions = GetSelectList();
return View(viewModel);
}
View
#model PathToYourViewModel.ViewModel
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedRoomId, Model.RoomOptions, "-- select an option --")
<button type="submit">Submit</button>
};
Tried and tested. Good luck!
The model binding takes place with help of the names property in mvc .
In your case the name of your control is BuildingList:
#Html.DropDownList("BuildingList", (SelectList)ViewData["BuildingList"])
Therefore at your controller Action will go as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection collection)
{
var selectedValue = collection["BuildingList"];
}