MVC ddl value after postback - model-view-controller

I have a ddl which is populated with hours of day 01-23. This is on a form which is used to book an item of equipment. The hour is populated to a db field. The issue is this, when the booking form is opened to alter the time the ddl shows the hour that was booked, when changed though and the form is submitted the value passed on post is the initial value from db not the new selected hour.
this is the basic pieces of code. any idea why the newly selected ddl value is not passed to the model??
View
<%= Html.DropDownList("ddl_Hour", Model.ddlHour,
new { #class = "DropDown", style = "width: 40px” })%>
Model
private string _ddlHourSelectedValue = "0";
public SelectList ddlHour
{
get
{
return (new System.Web.Mvc.SelectList(_ddlHour, "intValue", "Text", Convert.ToInt32(_ddlHourSelectedValue)));
}
}
public string ddlHourSelectedValue
{
get
{
return _ddlHourSelectedValue;
}
set
{
_ddlHourSelectedValue = value;
}
}
param[6] = new SqlParameter("#Timeslot", ddlHourSelectedValue);

The field in your view is called "ddl_Hour" However is there a variable in your Model with the same name? Otherwise the MVC framework will not automatically populate the value in the model.
Two ways you could go about this.
1
In your controller methods that accepts a post, you can add the parameter: FormCollection fc to the method. This key value pair collection will allow you to fetch results from fields in the post data like so:
string selectedValue = fc["ddl_Hour"];
2
Or you can modify your model to include a variable with the same name as the drop down list so that it is automatically populated for you.
public string ddl_Hour { get; set; }
You should then be able to access the result of the drop down list selection on post from that variable.

Related

How could i dynamically bind data in checkbox in mvc3 razor

I am working in mvc3 razor.
i want checkbox input in razor view for all catagories stored in database.
how could i bind it? please help
Suppose your model is having a field to hold all the checkbox text like.
public class MyClass
{
public string SelectedOptions {get;set;}
public List<String> CheckList {get;set;}
}
Write a controller Action method like
public ActionResult ShowCheckBoxList()
{
MyClass Options= new MyClass();
Options.CheckList = new List<String>();
// Here populate the CheckList with what ever value you have to
// either if you are getting it from database or hardcoding
return View(Options);
}
you have to create a view by right clicking the above method and choose Add View. Make sure you keep the name same as the method name also you the strongly typed view by choosing the MyClass Model from the dropDown, scaffolding template is optional use it as per your scenario.
Now in your View you can use this populated check box text as
#foreach(var optionText in Model.CheckList)
{
#Html.CheckBox(#Model.SelectedOptions, false, new {Name = "SelectedOptions", Value = #optionText})
#Html.Label(#optionText , new { style = "display:inline;" })
}
Keep this in a form and make sure you also specify a Action to be called on post of the form.
Make your action name same as the previous action (it is [GET] meaning before post), Now we create same method for [POST]
[HTTPPOST]
public ActionResult ShowCheckBoxList(MyClass data) // here you will get all the values from UI in data variable
{
//data.SelectedOptions will have all the selected values from checkbox
}

MVC3 DropDownListFor not setting selected property

In MVC3, when using DropDownListFor is it necessary for the first parameter to be a string? I have the following setup:
#Html.DropDownListFor(m => m.MyListItemId, Model.MyListItems,
new Dictionary<string, object>
{
{ "style", "width:120px" },
{ "data-type", "myList" }
})
where m.MyId is an int on my viewmodel. I'm having an issue where when I change the selected item in my drop down list, and inspect the rendered html, the "selected" property is not set to the newly selected item. This is a problem as i'm using jquery clone function to copy that row and i need the list with the new selected item to be copied to my new row. Ideas?
Update - Changing the property on the viewmodel to a string makes no difference.
Is this a bug with mvc dropdownlistfor? I've read quite a few posts on similar issues, but can't seem to find a solution that works in this instance. This is how my list is setup in my code:
var myListItems = _myRepository.GetAll();
model.MyListItems = new SelectList(myListItems, "Id", "Name", lineItem.myListItemId);
model.MyListItemId = lineItem.myListItemId;
where lineItem is passed into this method
No, the selected value property does not need to be a string, it can be an int. As long as the value is convertible to a string, it should work (so selected value type could be a Guid, int, bool, etc).
I have sometimes found issues when my route for the page has a route parameter with the same name as the selected value model property. For example, consider this:
route: "/establishments/{establishmentId}/edit"
Model:
public class MyViewModel
{
public int EstablishmentId { get; set; }
public SelectListItem[] Establishments { get; set; }
}
View:
#Html.DropDownListFor(m => m.EstablishmentId, Model.Establishments)
With this code, the selected value of the drop down list would always be whatever establishmentId is in the route. So if the route were /establishments/12/edit, then value 12 would be selected in the dropdown. It doesn't matter that the route parameter and model property capitalization doesn't match.
I figured this out by downloading the MVC source code, making my own copy of the DropDownListFor (named MyDropDownListFor), then stepping through the code to see what happened. If you are still having trouble with MVC3, I suggest you do the same. You need to figure out whether this is an issue with the server code, or your jquery clone stuff.

How to pass value from one action to another action having different views in mvc3

Hi I am developing an application in MVC3.
and i am stuck at one place.
I have 2 fields in my view which are not a part of my class.
i am just using them to populate the dropdown
The 2 fields are State and District.
But i want to show the selected value of the two fields in another View.
I tried it using ViewBag but this doesnot work and gives me Null.
this is inside Create get method:
int stateid = Convert.ToInt32(formcollection["ProvincialState.ProvincialStateID"]);
int districtid = Convert.ToInt32(formcollection["District.DistrictID"]);
ProvincialState state = new AddressService().FetchStateByStateId(stateid);
District district = new AddressService().FetchDistrictByDistrictId(districtid);
ViewBag.State = state.ProvincialStateName;
ViewBag.District = district.DistrictName;
and this is inside Details View:
string data1 = ViewBag.State;
string data2 = ViewBag.District;
ViewBag.State = data1;
ViewBag.District = data2;
I cannot use post method of Create coz i need to show this data only on another view.
or if is their any method thru which i can show the data in the same view.
ViewBag is like ViewData. In order to have information between pages you should store that info in session. You can do that in 2 ways:
Use a session variable like:
this.Session["SessionVariable"] = value;
Or use the this.TempData object:
this.TempData["SessionVariable"] = value;
The difference between this two is that the TempData object will be deleted from the session when it is read.
TempData is just a wrapper of the session.
You can send this fields to your action in addition to model, and then store it in session for example:
public class SomeController: Controller
{
[HttpPost]
public ActionResult DoSomething(MyModel model, int state, int district)
{
// validating model...
// ...
Session["state"] = state;
Session["district"] = district;
// some other logic...
}
}

Dynamically create random number of dropdownlists in MVC

I need to create a random number of dropdownlists in my view, based on the selected value of another dropdownlist. This is all done but my problem comes when I need to make the httppost because i never know how much data i need to save in my db.
In my model I have a list
public List<RoomToBooking> RoomsToBooking { get; set; }
that will get filled with x number of RoomToBooking when the Create view is rendered after the user makes a selction of dropdownlist 1:
var dogs = from d in db.Dogs
where d.Customer_ID == id
select d;
foreach (Dog item in dogs)
{
roomToBooking = new RoomToBooking();
roomToBooking.Customer_ID = id;
roomToBooking.Dog = item;
roomsToBookingList.Add(roomToBooking);
}
So I would like to create the same number of dropdownlist in my Create view
#Html.DropDownListFor(model => model.Booking.RoomToBooking, new SelectList(ViewBag.DeliveryTypes), new { #class = "selectbox" })
#Html.ValidationMessageFor(model => model.Booking.RoomToBooking)
So I in the end can be able to save it to my db
[HttpPost]
public ActionResult Create(EditBookingPensionViewModel model)
{
foreach (RoomToBooking item in objViewModel.RoomsToBooking)
{
//Save to db
}
}
I assume that I should use jquery to create the dropdownlists, but how do i create the dropdownlists so the selected values can be found in my viewmodel??
You may take a look at the following article. I slight adaption might be necessary for your scenario because you don't have add and remove buttons but instead you use the selected value of a dropdownlist to determine the number of dynamic rows to be added. But the concept is the exactly the same.

Preselection in a DropDownList

I'm just starting with MVC3 and I have the following situation.
My app's initial sign up page among other controls contains a drop down menu. When the user has completed the form then the form details are saved in a session and they move on to the next step. They may also move back to the original step to re-edit, in which case I need to show the drop down menu with the appropriate value preselected.
My code is as follows:
Controller:
public ActionResult Index()
{
var model = new CompanyDetailsModel();
BindDropDownLists(model);
//IF WE HAVE A SESSION THEN PREFILL THE VALUES
if(MySession.Current.IFA!=null)
model = EditIFAProfileService.returnCompanyDetailSession(MySession.Current.IFA);
return View("CreateCompanyDetails", model);
}
I am getting the expected values from the model, so for example the
value model.Salutation is equal to an integer.
So, armed with that value I would expect to be able to set the preselected value of my dropdownlist as follows:
#Html.DropDownListFor(model => model.SalutationValue, Model.SalutationItems,
"Please Select", new { #tabindex = "1" })
If I do set the model value of SalutationValue to an int then I get an error stating that
ViewData item that has the key is of type 'System.Int32' but must be of type 'IEnumerable'.
Any help would be much appreciated.
Thank you.
Don't use any ViewData if you are working with strongly typed views and view models as it would conflict. Simply set the SalutationValue property to some given value. Here's an example:
public ActionResult Index()
{
var model = new CompanyDetailsModel();
model.SalutationItems = ...
if (MySession.Current.IFA != null)
{
model.SalutationValue = MySession.Current.IFA;
}
return View("CreateCompanyDetails", model);
}

Resources