MVC Razor - How to update a multiple rows in a selected column from a dropdown list SQL - 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
}

Related

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)

dropdownlist selection returning null # mvc4

I am trying to insert to database from view page which has dropdownlist , textbox's .. when i enter something and click on save means i am getting nothing from dropdown selection which is binded .
My code :
#model IEnumerable<iWiseapp.Models.LObmodel>
#using (#Html.BeginForm("stop", "Home", FormMethod.Post))
{
#Html.DropDownList("Data",ViewBag.Data as SelectList,"select a sdsd",new {id="LOB_ID"})
#Html.DropDownListFor("sss",new SelectList(Model,"lob_id","lob_name"))
,
#Html.DropDownList("LObmodel", new SelectList(ViewBag.data ,"Value","Text"))
#Html.DropDownListFor(model => model.lob_name, new SelectList(ViewBag.Titles,"Value","Text"))
I tried above all possibilities but nah i am confused nothing working out
ADDED MY CONTROLER CODE
[HttpGet]
public ActionResult stop()
{
ServiceReference1.Service1Client ser_obj = new ServiceReference1.Service1Client();
IEnumerable<LobList> obj = ser_obj.GetData(); //i am Getting list of data through WCF from BUSINESS LAYER WHERE i created entities via EF
List<SelectListItem> ls = new List<SelectListItem>();
foreach (var temp in obj)
{
ls.Add(new SelectListItem() { Text = temp.LOB_NAME, Value = temp.LOB_ID.ToString() });
}
//then create a view model on your controller and pass this value to it
ViewModel vm = new ViewModel();
vm.DropDown = ls; // where vm.DropDown = List<SelectListItem>();
THE COMMENTED CODE BELOW IS WHAT I AM DOING
//var mode_obj = new List<LObmodel>();
//Created LOBmodel class in model which is excat same of entities in Business class
//var jobList = new List<SelectListItem>();
//foreach (var job in obj)
//{
// var item = new SelectListItem();
// item.Value = job.LOB_ID.ToString(); //the property you want to display i.e. Title
// item.Text = job.LOB_NAME;
// jobList.Add(item);
//}
//ViewBag.Data = jobList;
return View(jobList); or return view (obj)
}
Any expert advice is appreciated
MY FIELDS , IS THESE PERFECT
public class template
{
public List<LobList> LOBs { get; set; } //LOBLIST FROM Entities in business layer
public int selectedLobId { get; set; }
public LobList SelectedLob
{
get { return LOBs.Single(u=>u.LOB_ID == selectedLobId) ;}
}
}
AND
public class LObmodel
{
public int LOB_ID { get; set; }
public string LOB_NAME { get; set; }
}
I would recommend putting the selectlist into your model instead of passing it through the view bag. The option you want is
#Html.DropDownListFor(model => model.lob_name, new SelectList(ViewBag.Titles,"Value","Text"))
you can set the selected item by setting model.lob_name on the controller and on post back that value will be set to the selected value of the dropdown
on your controller you can build the list like this
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in model){ //where model is your database
ls.Add(new SelectListItem() { Text = temp.Text, Value = temp.Value });
}
//then create a view model on your controller and pass this value to it
LObmodel vm = new LObmodel();
vm.DropDown = ls; // where vm.DropDown = List<SelectListItem>();
return View(vm);
then on your view you can reference that
#Html.DropDownListFor(x => x.lob_name, Model.DropDown)
with your model add the select list
public class LObmodel
{
public int LOB_ID { get; set; }
public string LOB_NAME { get; set; }
public List<SelectListItem> DropDown { get; set; }
}
then the top of your view would be
#model LObmodel
I had the same problem .
But i changed the view code of DDL using this code :
#Html.DropDownListFor(x => x.ClassID, (SelectList)ViewBag.ClassName);
The dropdownlist will bind to your model class called ClassID You will not be able to post the textual value of the ddl to the controller, only the ID behind the ddl.

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)

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"];
}

not working dropdown list in edit view in mvc4 razor

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?