dropdownlist selection returning null # mvc4 - asp.net-mvc-4

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.

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
}

Model is Null in Httppost mvc

My Model is
public class IssueEntryModel
{
public IEnumerable<SelectListItem> OrderNumbers { get; set; }
public string SelectedWorkOrder { get; set; }
public string MaterialCode
{
get; set;
}
public List<GroupedIssueData> MaterialData { get; set; }
}
And the view is
#model InventoryEasy15.Models.IssueEntryModel
#{
var issueData = Model.MaterialData;
var workorders = Model.SelectedWorkOrder;
}
#using (Html.BeginForm("SaveIssueEntry", "IssueMaster", FormMethod.Post, new { id = "issueEntryForm" }))
{
#for (int i = 0; i < issueData.Count(); i++)
{
<tr>
<td>#issueData[i].MaterialCode</td>
<td>#issueData[i].MaterialDescription</td>
<td>#issueData[i].Unit</td>
<td>#issueData[i].ReqQty</td>
<td>#Html.TextBoxFor(m => issueData[i].IssueQty, new { style = "width:70px" })#Html.ValidationMessageFor(m => issueData[i].IssueQty)</td>
<td class="text-center">#Html.CheckBoxFor(m => issueData[i].isSavings)</td>
</tr>
}
And I have post method as
public ActionResult SaveIssueEntry(IssueEntryModel model)
{
var result = new Dictionary<string, string>();
And the get contains the details to fill the view as
//Method Get the material details based on the work order id
public async Task<ActionResult> GetWorkOrderMaterialDetails(IssueEntryModel m)
{
During post to a new method , the model is becomes null, Any thoughts?
Razor uses the expression passed to the HTML helpers in order to build the proper name for the inputs that will allow the modelbinder to bind them properly on post. That means the expression needs to match the access method of the property exactly. By saving Model.MaterialData to the issueData variable and utilizing that, you're disrupting this. In other words, you're ending up with inputs named like issueData[0].IssueQty, instead of MaterialData[0].IssueQty. The modelbinder doesn't know what to do with issueData on post, because nothing on your model matches that.
Long and short, your textbox needs to be declared like:
#Html.TextBoxFor(m => m.MaterialData[i].IssueQty, ...)
Similarly for your checkbox:
#Html.CheckBoxFor(m => m.MaterialData[i].isSavings)

How to bind a drop down with a model property while containing the list items of that drop down?

I am stuck in a problem, I have retrieved all the value for a drop down in a view bag and want to display them at run time. I have achieved it by using the following code for the controller
[HttpGet]
public ActionResult Index()
{
var categoryList = new PersonalApp();
SelectList catList = new SelectList(categoryList.GetAffinity().ToList(), "ClientName", "AffinityNum");
ViewBag.categoryList = catList;
return View();
}
and the following code for the view
#using (Html.BeginForm("index", "Home"))
{
#Html.DropDownList("categoryList", "Branch Type")
}
It really works but now I want to bind it with a model now. I have use the following code for this:
#Html.DropDownListFor(model=>model.AffinityNum, "categoryList", "BranchType")
But it gives me an error as CategoryList cannot be used as a parameter with the above code. How will I get this resolved as I can have all the values of a dropdown in the categorylist and I can bind it with a model property affinityNum with it as well.
Thanks
Your model should have an IEnumerable<SelectListItem> property that will hold the values:
public class PersonalApp
{
public string AffinityNum { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
that you will populate in your controller action and pass to the view:
[HttpGet]
public ActionResult Index()
{
var model = new PersonalApp();
var categories = categoryList.GetAffinity().ToList();
SelectList catList = new SelectList(categories, "ClientName", "AffinityNum");
model.CategoryList = catList;
return View(model);
}
and finally in your strongly typed view you will use this property to bind the dropdown list to:
#model PersonalApp
...
#Html.DropDownListFor(x => x.AffinityNum, Model.CategoryList, "BranchType")
Please try;
#Html.DropDownListFor(model=>model.AffinityNum, (SelectList)ViewBag.categoryList)

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

What is the best way to create dropdownlists in MVC 4?

I want to know,What is a best way to create dropdownlists in MVC 4?
With ViewBag or another approach?
I would argue that since the items are variable values within your view that they belong in the View Model. The View Model is not necessarily just for items coming back out of the View.
Model:
public class SomethingModel
{
public IEnumerable<SelectListItem> DropDownItems { get; set; }
public String MySelection { get; set; }
public SomethingModel()
{
DropDownItems = new List<SelectListItem>();
}
}
Controller:
public ActionResult DoSomething()
{
var model = new SomethingModel();
model.DropDownItems.Add(new SelectListItem { Text = "MyText", Value = "1" });
return View(model)
}
View:
#Html.DropDownListFor(m => m.MySelection, Model.DropDownItems)
Populate this in the controller or wherever else is appropriate for the scenario.
Alternatively, for more flexibility, switch public IEnumerable<SelectListItem> for public IEnumerable<MyCustomClass> and then do:
#Html.DropDownFor(m => m.MySelection,
new SelectList(Model.DropDownItems, "KeyProperty", "ValueProperty")
In this case, you will also, of course, have to modify your controller action to populate model.DropDownItems with instances of MyCustomClass instead.