enable html dropdown through controller in mvc - asp.net

i have an scenario where i have to perform some action according to selection of the
dropdown .
for basic refrence you can use the example of country,state,city.
i am able to populate the country list at that time i have set the other two drop downs to
disable.
after the countries are populated i want to select the state.it is getting populated .
two problems
1) how to retain the state of country ddl as it is coming back to its orisnal state.
2) how to enable the drop down through my controller.
myview code
Country
<p>
<label>
State</label>
<%=Html.DropDownList("ddlState", ViewData["ddlState"] as SelectList, "--not selected--",new { onchange = "document.forms[0].submit()", disabled = "disabled" })%>
</p>
<p>
<label>
City</label>
<%=Html.DropDownList("ddlCities", ViewData["ddlCities"] as SelectList, "--not selected--", new { onchange = "document.forms[0].submit()", disabled = "disabled" })%>
</p>
my controller code
public ActionResult InsertData()
{
var customers = from c in objDetailEntity.Country
select new
{
c.Cid,
c.Cname
};
SelectList countriesList = new SelectList(customers.Take(100), "Cid", "Cname");
ViewData["ddlCountries"] = countriesList;
SelectList EmptyState = new SelectList(customers);
ViewData["ddlState"] = EmptyState;
ViewData["ddlCities"] = EmptyState;
Session["ddlSesCountry"] = countriesList;
return View();
}
//
// POST: /RegisTest/Create
[HttpPost]
public ActionResult InsertData(FormCollection collection)
{
try
{
CountryId = Convert.ToInt16(Request.Form["ddlCountries"]);
stateid = Convert.ToInt16(Request.Form["ddlState"]);
if (CountryId > 0 && stateid <= 0)
{
var stateslist = from c in objDetailEntity.State
where c.Country.Cid == CountryId
select new
{
c.Sid,
c.Sname
};
SelectList stateList = new SelectList(stateslist.Take(100), "Sid", "Sname");
ViewData["ddlState"] = stateList;
Session["StateList"] = stateList;
ViewData["ddlCities"] = stateList;
}
if (stateid > 0)
{
var citieslist = from c in objDetailEntity.City
where c.State.Sid == stateid
select new
{
c.Ctid,
c.Cityname
};
SelectList cityList = new SelectList(citieslist.Take(100), "Ctid", "Cityname");
ViewData["ddlCities"] = cityList;
ViewData["ddlState"] = Session["StateList"];
}
ViewData["ddlCountries"] = Session["ddlSesCountry"];
return View();
}
catch
{
return View();
}
}

My choice would be not to post back the form at all. I would write an action in the controller that takes a CountryID and returns a JsonResult holding a list of states. The onchange event could call a jQuery function that uses AJAX to call this action, loads the new list, and enables the second drop-down list.
However, if you stick with the postback, here's why it's not working:
The Country list isn't retaining its selected value because the view is being reloaded from scratch each time and you're setting it to "not selected." The SelectList constructor has an overload that takes a "SelectedItem" object as the fourth parameter. When you initialize your SelectList, you should pass the appropriate value to this parameter, and not force it in the View.
You need to write an "if" clause in your View to choose whether or not to enable the list based on some criteria. You could bind to a ViewModel that has a Boolean property like "EnableStates," or you could use something like the count of values in the StateList - if the count is greater than zero, enable it, for example.
A tricky thing to get used to when you move from Web Forms to MVC is that you don't have ViewState anymore - your application is stateless. There's nothing that "remembers" what value is selected in a drop-down for you, you have to set it each time you load the page.

I recommend using JSON & jQuery - like this posted answer.

Related

Xamarin Form passing parameters between page keep a hard link to it

I try the new Shell of Xamarin Form 4 for a small project.
I have a list of order, then someone chooses an order and start picking some inventory for this order with barcode. To be simple, I use 2 views and 2 viewmodel.
The process is:
1. User select an order the click a button "pickup"
2. I use ViewModelLocator (TinyIoc) to resolve the correct ViewModel of the pickup view
3. I call Initialize on the new ViewModel and pass some parameters needed. Like a list of items needed to be pickup.
4. Open the view in modal state.
I don't understand that if I change some qty in the list I pass on the second viewmodel, then hit the back button (modal view close). The quantity changed is now in the original viewmodel. How this is possible? I was thinking that passing parameter to a function do not share the same variable but just copy it??
Viewmodel of the first view (look at the Initialize function the List passed and the JobEnCours object)
private async Task GoPickup()
{
Device.BeginInvokeOnMainThread(async () =>
{
if (this.CodeJob != null && this.CodeJob != "")
{
this.IsBusy = true;
PrepChariotSP3ViewModel vm = ViewModelLocator.Resolve<PrepChariotSP3ViewModel>();
await vm.InitializeAsync(this._jobEnCours, this.ComposantesPick.ToList()) ;
await Shell.Current.Navigation.PushAsync(new PrepChariotSP3Page(vm));
this.IsBusy = false;
}
});
}
the the Initialize code on the second Viewmodel (look I set the JobEnCours.Description=Test)
public async Task InitialiseAsync(Job jobEnCours, List<ComposantePick> composantePick)
{
Title = "Ceuillette: " + jobEnCours.CodeProd;
this._jobEnCours = jobEnCours;
this.ComposantesPick = new ItemsChangeObservableCollection<ComposantePick>();
foreach(ComposantePick c in composantePick)
{
this.ComposantesPick.Add(c);
}
jobEnCours.Description = "test";
So, If I do the back button, then in the first VM the JobEnCours.Description is now set to "test" how this is possible?!
Any idea?

Kendo UI Dropdown List default value from data

I am trying to set Value or SelectedIndex based on the datasource return after Read.
This is my View
#(Html.Kendo().DropDownList.
Name("ddlUsers").
DataTextField("text").
HtmlAttributes(New With {.style = "width:500px"}).
DataValueField("id").
DataSource(Sub(s)
s.Read(Sub(r) r.Action("GetUserList", "Employees")
End Sub). ServerFiltering(True)
End Sub).Events(Sub(e) e.Change("SetHiddenUGID")) )
The method GetUserList looks like this
Shared Function GetUserList() As IList
Return db.GetDBUserList().Where(Function(w) w.value <> 0).Select(Function(s) New With {.id = s.value,.text = s.text,.isdefault = s.isdefault}).ToList()
End Function
Now GetDBUserList returns a List of Employees
Public Class Employees
Public Property value As Int64
Public Property text As String
Public Property isdefault As Int32
End Class
I want to set the default value of the dropdown based on isdefault when it's 1, any ideas?
I have tried
var dropdownlist = $("#ddlUsers").data("kendoDropDownList");
dropdownlist.select(function (dataItem) {
if (dataItem.isdefault === 1) {
$("#ddlUsers").data("kendoDropDownList").value(dataItem.id);
}
});
But it did not work.
Your DropDownList is bound to remote data, so you cannot attempt to set the value until after your read action returns with the data.
So, you have to add your code to select the default item in the dataBound event of the DropDownList, as there is not data to select until that point.
But, your function is attempting to set the value to dataItem.id...your model does not have an id field...it has value, text, and isdefault.
Also, the DropDownList select() method takes jQuery selector, an index, or a function that returns a boolean (http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#methods-select). Your function does not return anything...so it would result in nothing being selected.
Try doing this in the dataBound event of the DropDownList:
dataBound: function(e) {
var data = e.sender.dataSource.data();
e.sender.select(function (dataItem) {
return (dataItem.isdefault === 1);
});
}
Here's a working example: http://dojo.telerik.com/#Stephen/inUKI
It's using javascript initialization but you can add the dataBound event handler to your Razor initialization easily.

How can I send a list in BeginForm()?

Can someone please help me with this problem? At the bottom of my view just before the page loads I create an array of checkboxes like this:
foreach (var course in courses.Select((x, i) => new { Data = x, Index = i }))
{
int currentIndex = course.Index;
String selectedday = "";
String selectedteacher = "";
if (cnt++ % 4 == 0)
{
#: </tr> <tr>
}
#: <td >
<br /><br /><br />
<input type="checkbox" id="checkbox"
name="selectedCourses"
value="#course.Data.CourseID"
#(Html.Raw(course.Data.Assigned ? "checked=\"checked\"" : ""))
/>
I use the same loop to add the assigned state to a list like this:
bool theNewString=course.Data.Assigned ;
String a=theNewString.ToString();
assignedCourses.Add(a);
I defined a list variable at the top of the page so that it can be accessed by the form-wide like this:
#{List<String> assignedCourses =new List<String>(); }
Now I want to send that variable to the controller and this is where things get muddy. If I send a string like this it works fine:
Razor markup
String postedData = "literalString";
#using (Html.BeginForm("Action", "Controller", new { assigned = # postedData }))
Action
[HttpPost]
public ActionResult Edit(int id,List<String> assigned){}
Now if I try this:
#{List<String> assignedCourses =new List<String>(); }
#using (Html.BeginForm("Action", "Controller", new { assigned = #assignedCourses }))
And nothing comes through to the controller. It’s like the list is emptied just before posting. How can send my list to the controller?
I think the way you are trying to create the query string/postback url for the form using the list is wrong and will not produce a properly formatted string.
Maybe try something like this:
#{
List<string> ExampleList = new List<string>();
ExampleList.Add("True");
ExampleList.Add("False");
string param = string.Join("&", ExampleList.ToArray());
}
#using (Html.BeginForm("index", "home", new { #someparam = (new HtmlString(param)) })) { }
This would require you to split the single string up into an array when the action method receives it.
alternatively you can try using RouteValueDictionary instead of list, but this does not support duplicate keys.
Also for checkbox creation try using #Html.CheckBox() as this will automatically create a second hidden input set to false. HTML Forms don't post back checkbox values when they are unchecked, so the second hidden input with the same name will be posted back and you will know it has been unchecked or not checked. MVC will interpret values of "True, False" for the same form key/input name as True and False when just the hidden input with the "False" value is posted back.

get the select element in .NET using AJAX

I have ajax function like this to run on HTML select list
$.ajax({
type: "POST",
url: urlemp,
success: function (returndata) {
if (returndata.ok) {
// var data = eval("" + returndata.data + "");
select.empty();
select.append($('<option>' + "" + '</option>'));
$.each(returndata.data, function (rec) {
select.append($('<option>' + returndata.data[rec].Name + '</option>'));
});
select.show('slow');
select.change();
}
else {
window.alert(' error : ' + returndata.message);
}
}
}
);
and this is the HTML element
<select id="cmbDept"></select>
How can i get the value of the selected item in the controller using MVC 3 ?
you have 4 ways to do that
1. the you can bind ti the change event of the select $(select).change(function(){}) and send an ajax request again wrapping the selected value which you will be able to get in the controller
2. you can keep a hidden input in your view binded to a property in the view's model now bind to the change of the select and fill the input with the value this way whenever your form is posted back it will have the values properly binded to the model
3. #Don saved me from writing the third way so read his ans.
4. if you have a model that this view is binded to then simple keep a property in the model with the name cmbDept and selected value would be automatically posted back
Us FormCollection as parameter in your controller. And assign name to the select
<select id="cmbDept" name="cmbDept"></select>
Now the FormCollection has this posted value.
public ActionResult Index(FormCollection form)
{
string val = "";
foreach (var key in form.AllKeys)
{
if (key.Contains("cmbDept"))
{
val = form.Get(key);
}
}
--your code here with the posted values
return View();
}
To get the value of the select element on the client, just use $("#cmbDept").val().
To get the value of the element once it's submitted to the server, add a name="cmbDept" to your select and simply create a parameter named cmbDept in the controller action your $.ajax call is is posting to.

ASP.Net MVC dropdown selected value

I have been dealing with the dropdownlist which i am able to populate but if i come back to edit a record, the dropdown is not showing the selected value.....
In controller,
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
int b = Convert.ToInt32(serviceToUpdate.ServiceID);
var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a,serviceToUpdate.ServiceID);
In view:
#Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
serviceToUpdate,ServiceID has the right value but somehow when I try to edit the selected value is not returned... instead the first value of dropdown is only returned...
I had the same problem. Use the null object pattern where you have a reserved id and the display name of the item is "please choose..." or something similar. Before passing in the model to the view, append to the beginning of the collection the null object. In the controller on the way back in, test for it. You can then set the property to null if the person didn't choose anything.
Here is my question:
DropDownListFor Not Displaying/Persisting Null for First Choice in List
You shouldn't have to use view data explicitly either like you are doing.
Code in Controller:
ViewBag.Services = new SelectList(a, "ServiceId", "#Servicename");
ServiceId is the property representing the key-value for the item displayed in the dropdown list
#Servicename stands for the property representing the text you want to display for the item in the dropdownlist)
Code in View:
#using(#BeginForm){
SelectList services = Viewbag.Services;
#Html.DropDownListFor(model => model.ServiceID, services)
}

Resources