It is possible to refresh ViewBag value in the view? - c#

I'm trying to do a dynamic dropdownlist :
I get the options of the dropdownlist from a database and put them in an objects list. In accordance with a checkbox value i remove objects from the list and set this list as a ViewBag value.
public ActionResult ThematicManagement(string Id, string IsAdult, string flagAdult)
{
.....
ViewBag.DDL = null;
var response = VodCatalogBUS.GetParentThematics();
List<oboThematic> list = new List<oboThematic>();
list = response.Data;
if (IsAdult == null || IsAdult == "false")
list.RemoveAll(x => x.IsAdult == true && x.Id != 1007);
else
list.RemoveAll(x => x.IsAdult == false && x.Id != 1007);
ViewBag.DDL = new SelectList(list, "Id", "Name");
....
Then in my view i fill the dropdownlist like that :
#Html.DropDownList("ParentThematic", (SelectList)ViewBag.DDL, new { #class="dropdown" })
<label><input type="checkbox" value="" id="ChkIsAdult" name="ChkIsAdult">Adulte</label>
There is no problems here, i obtain the dropdown list with 4 options after the RemoveAll in the controller. Then if i click the checkbox, i must obtain 3 other options.
So I use an ajax call to return into the controller in the aim to update Viewbag's value :
$('#ChkIsAdult').change(function () {
var IsAdult = $('#ChkIsAdult').is(':checked');
var url = dev + "/Legacy/ThematicManagement";
$.ajax({
url: url,
cache: false,
type: 'POST',
data: {
IsAdult: IsAdult,
flagAdult : 'true',
},
success: function () {
alert('test');
}
});
})
It works i return into the controller, but i think that the view isn't refresh so i retreive the old values (the 4 options) of the dropdownlist after clicking the checkbox.
I also try with ViewData and TempData to replace ViewBag but i've always the same proprem !
According to you, it is the good solution ? Can it works ?

Here is the response :
Controller
var response = VodCatalogBUS.GetParentThematics();
List<oboThematic> list = new List<oboThematic>();
list = response.Data;
list.RemoveAll(x => x.IsAdult == true && x.Id != 1007);
var responseAdult = VodCatalogBUS.GetParentThematics();
List<oboThematic> listAdult = new List<oboThematic>();
listAdult = responseAdult.Data;
listAdult.RemoveAll(y => y.IsAdult == false && y.Id != 1007);
ViewBag.DDL = new SelectList(list, "Id", "Name");
ViewBag.DDLAdult = new SelectList(listAdult, "Id", "Name");
View :
#Html.DropDownList("ParentThematic", (SelectList)ViewBag.DDL, new { #class="dropdown" })
#Html.DropDownList("ParentThematicAdult", (SelectList)ViewBag.DDLAdult, new { #class="dropdown" , #style="display:none"})
JS :
$('#ChkIsAdult').change(function () {
if ($('#ChkIsAdult').is(':checked')) {
$('#ParentThematic').hide();
$('#ParentThematicAdult').show();
var value = $('#ParentThematicAdult').val();
var IsAdult = $('#ChkIsAdult').is(':checked');
var url = dev + "/Legacy/ThematicManagement";
$.ajax({
url: url,
cache: false,
type: 'POST',
data: {
Id: value,
IsAdult: IsAdult
},
success: function (data) {
$('#result').empty().append($(data).find('table'))
}
});
}
else
{
$('#ParentThematic').show();
$('#ParentThematicAdult').hide();
var value = $('#ParentThematic').val();
var IsAdult = $('#ChkIsAdult').is(':checked');
var url = dev + "/Legacy/ThematicManagement";
$.ajax({
url: url,
cache: false,
type: 'POST',
data: {
Id: value,
IsAdult: IsAdult
},
success: function (data) {
$('#result').empty().append($(data).find('table'))
}
});
}
})

Related

MVC 5 Select list - user input

I am using the following to generate a dropdownlist of provinces based on the country selection:
<select id="Province" name="Province" class="form-control input-sm">
#{
string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName = null;
}
#{
if (Model != null && !String.IsNullOrEmpty(Model.Province))
{
selectedProvinceName = Model.Province;
}
else
{
selectedProvinceName = ConfigData.DefaultProvinceName;
}
}
#foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName
? "selected=\"selected\""
: String.Empty;
<option value="#(anEntry)" #(selectedTextMark)>#(anEntry)</option>
}
</select>
The challenge is I don't have a list of provinces (states) for other countries! Is there a way to allow for the user to type in the name of the province? Like a combobox.
I had to do it using Knockout-Kendo combobox, here is the solution:
Controller:
public ActionResult Index()
{
ViewBag.CountryID = new SelectList(db.Countries, "ID", "Name", "34");
.....
public JsonResult GetState(int? id)
{
if (id == null)
{ id = 34; }
var data = db.States.Where(x => x.CountryID == id)
.Select( x =>
new
{
ID = x.ID,
Name = x.Name
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
In the View:
#Html.DropDownList("Country", ViewBag.CountryID as SelectList, "Select...",
new { onchange = "UpdateProvinces();" })
<input data-bind="kendoComboBox: { dataTextField: 'Name', dataValueField: 'ID',
data: choices, value: selectedChoice }" />
Here is the JavaScript:
function UpdateProvinces() {
var countryId = $("#Country option:selected").val();
$.getJSON("/Home/GetState/" + countryId,
null,
function (data) {
objVM.choices(data);
});
}
function ItemViewModel(arg) {
arg = 34;
var self = this;
this.choices = ko.observableArray([]),
$.ajax({
type: "GET",
url: '#Url.Action("GetState", "Home")',
contentType: "application/json; charset=utf-8",
data: { id: arg },
dataType: "json",
success: function (data) {
self.choices(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
var selectedChoice = {
ID: self.ID,
Name: self.Name
};
self.selectedChoice = ko.observable();
}
var objVM = new ItemViewModel();
ko.applyBindings(objVM);
Edit:
Another alternative is to use Telerik MVC UI Combobox http://demos.telerik.com/aspnet-mvc/combobox/cascadingcombobox

Passing value to the controller as a parameter through ajax call

View
function editEmployee(val) {
var a = ko.toJSON(val);
// alert("Hi");
$.ajax({
url: "#Url.Action("editEmployee", "Registration")",
contentType: "application/json; charset=utf-8",
type: "POST", dataType: "json",
data:a,
success: function (data) {
// alert("awa");
debugger;
DisplayUI.getEmpArray(data);
var abc = DisplayUI.getEmpArray();
}
});
}
Controller
[HttpPost]
public JsonResult editEmployee(string ID)
{
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//dynamic item = serializer.Deserialize<object>(ID);
var employee = from s in db.Employee
select s;
try
{
if (!String.IsNullOrEmpty(ID))
{
employee = employee.Where(s => s.empId.Contains(ID));
}
}
catch (Exception ex)
{
}
var val = Json(employee.Select(s => new { s.empId, s.firstName, s.lastName, s.mobilePhn, s.email, s.desigId }).ToList());
return val;
}
Through ajax call I'm passing the value into controller as a string variable(ID). But that value is not passing it is visible as null value. I want to know get the value as a parameter what i should do.
Check whether you are getting json object
var a = ko.toJSON(val); // here you should check whether you are getting json object
Only if you get json object,the value will be bind to the controller.
put alert like this
var a = ko.toJSON(val);
alert(a);
if it is json object it will show like this
[object],[object]

MVC and JQuery Load parameter List

I have a JQuery function that load some data from C# and update information on my view.
I must to load a large dataset and all works fine, but for some reason i must to load a dynamic list and elaborate its from JQuery.
The list is "listCasistiche" and when i load it from MVC the JQuery function goes in error.
How can i take this list?
The JQuery function is this:
var data = $('#jqxgrid').jqxGrid('getrowdata', rowindex);
var uf = new FormData();
uf.append("id", data.Id);
var url = "/Clienti/LoadSelezionato";
$.ajax({
type: "POST",
url: url,
dataType: 'json',
contentType: false,
processData: false,
data: uf,
error: function () {
// The function go in error
},
success: function (result) {
if (result != "error") {
result.listCasistiche.forEach(function (entry) {
alert(entry.IdCasistica);
});
ricaricaNeri();
$('#OwnLead').val(result.ownerLead);
$('#dataLead').datepicker('setDate', result.dataLead);
}
}
});
The MVC LoadSelezionato function is this. All other parameters are loaded well:
[HttpPost]
public ActionResult LoadSelezionato(FormCollection form)
{
int id = Convert.ToInt32(form["id"]);
try
{
Cliente clienteLead = conc.Clientes.FirstOrDefault(x => x.Id == id);
if (clienteLead != null)
{
var elemento = new
{
ownerLead = clienteLead.OwnerLead,
dataLead = clienteLead.DataLead,
listCasistiche = conc.CasisticheClientes.Where(x => x.IdCliente == id).ToList()
};
return Json(elemento, JsonRequestBehavior.AllowGet);
}
else
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json("error", JsonRequestBehavior.AllowGet);
}
}
Thanks to all

Can't Filling DropDownList with Ajax in MVC

Everything seems OK but value shows empty..
I have 2 dropdownlist, when I choose first one, I got the index and used ajax to fill other dropdownlist.. But problem is that I dont have result.. loop that is in ajax, doesnt work.. and I checked web tool of firefox, result seems empty, but in C# code, the list has items..
so here is my ajax
$.ajax({
url: "#Url.Action("ElectionList", "Home")",
type: "GET",
dataType: "json",
data: { electionTypeId: selectedId },
success: function (data) {
if (data != null) {
//HERE IS WORKING
alert("OK");
electionCombo.html('');
$.each(data, function (index,item) {
//here is not working !!!
alert("hobaaa: " + index);
alert("data: " + item.Text);
// alert(option.ID + " " + option.politicName);
// electionCombo.append($('<option></option>').val(option.Value).html(option.Text));
});
}
here is my c# code
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult ElectionList(int electionTypeId)
{
var service = new EvoteServicesProviderClient();
try
{
var electtionType = service.getAllElectionTypes().FirstOrDefault(e => e.ID == electionTypeId);
var res =
service.searchElectionByType(electtionType.electionTypeName)
.ToList()
.Where(e => e.startDate >= DateTime.Now)
.Select(e => new SelectListItem
{
Value = e.ID.ToString(),
Text = e.politicName
});
var list = new SelectList(res, "Value", "Text");
return Json(list, JsonRequestBehavior.AllowGet);
// return Json(new { success = true, result = list },
// JsonRequestBehavior.AllowGet);
}
catch{}
return Json(new { success = false, message = "An error occured" }, JsonRequestBehavior.AllowGet);
}
this is the html side
#using (Html.BeginForm("ElectionList", "Home", FormMethod.Post, new {#class = "form-horizontal", id = "electionlistform"}))
{
#Html.LabelFor(m => m.SelectedElectionId, new {#class = "col-md-2 control-label"})
#Html.DropDownListFor(m => m.SelectedElectionId, Model.ElectionList, new {#class = "form-control", id = "electionList"})
#Html.ValidationMessageFor(m => m.SelectedElectionId)
}
As I wrote, the list is not empty (in actionresult ElectionList)
What I am missing?
Try this :
$.each(data, function () {
//here is not working !!!
alert("hobaaa: " + this.Value);
alert("data: " + this.Text);
});
You can access the property directly because it's json.
UPDATE
Just return the list server side :
var res =
service.searchElectionByType(electtionType.electionTypeName)
.ToList()
.Where(e => e.startDate >= DateTime.Now)
.Select(e => new SelectListItem
{
Value = e.ID.ToString(),
Text = e.politicName
});
return Json(res, JsonRequestBehavior.AllowGet);
What I do when I need to fill a dropdown is the same as you, but I'm using a for loop instead of each (maybe it's the same but for me it's working). And by the way, in your ajax code sample you are not closing the ajax function. Hope in your real code it's okay.
$.ajax({
url: "#Url.Action("ElectionList", "Home")",
type: "GET",
dataType: "json",
data: { electionTypeId: selectedId },
success: function (data) {
if (data != null) {
//HERE IS WORKING
alert("OK");
electionCombo.html('');
for (i in data) {
var result = data[i];
// electionCombo.append($('<option></option>').val(result.Value).html(result.Text));
}
}
});
By the way, if it's still not working , you could try a ViewModel with the options you need
public class ViewModelExample
{
public Int32 ValueOption { get; set; }
public String TextOption { get; set; }
}
And use it in your list instead of selectlist. With viewmodels I don't have problems getting the values with json.

on select change event - Html.DropDownListFor

I have two dropdownlist. The selected value from the first one loads the other. How do I do that when I have the helper methods in a controller?
#using (Html.BeginForm())
{
<div>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td><b>Select a District:</b></td>
<td>#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
<tr>
<td><b>Select a TM:</b></td>
<td>#Html.DropDownListFor(m => m.TMId, ViewData["TMManagers"] as IEnumerable<SelectListItem>, "Select One")</td>
</tr>
</table>
</div>
}
private void LoadDistrictManagers()
{
var _DMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "District Manager"
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["DMManagers"] = new SelectList(_DMS, "ChannelGroupId", "Name");
}
private void LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new { c.ChannelGroupId, c.Name }).OrderBy(m => m.Name);
ViewData["TMManagers"] = new SelectList(_TMS, "ChannelGroupId", "Name");
}
public ActionResult SummaryReport()
{
DistrictManagerModel model = new DistrictManagerModel();
LoadDistrictManagers();
return View("AreaManager", model);
}
Give both dropdowns unique IDs using the HTTPAttributes field:
#Html.DropDownListFor(m => m.DistrictId, ViewData["DMManagers"] as IEnumerable<SelectListItem>, "Select One", new {#id="ddlDMManagers"})
2nd dropdown should be initialized as an empty list:
#Html.DropDownListFor(m => m.TMId, Enumerable.Empty<SelectListItem>(), new {#id="ddlTMManagers"})
If you don't mind using jQuery ajax to update the 2nd dropdown when a 'change' event is triggered on the 1st dropdown:
$(function() {
$('select#ddlDMManagers').change(function() {
var districtId = $(this).val();
$.ajax({
url: 'LoadTerritoryManagers',
type: 'POST',
data: JSON.stringify({ districtId: districtId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$.each(data, function (key, TMManagers) {
$('select#ddlTMManagers').append('<option value="0">Select One</option>');
// loop through the TM Managers and fill the dropdown
$.each(TMManagers, function(index, manager) {
$('select#ddlTMManagers').append(
'<option value="' + manager.Id + '">'
+ manager.Name +
'</option>');
});
});
}
});
});
});
Add this class to your controller namespace:
public class TMManager
{
public int Id {get; set;}
public string Name {get; set;}
}
You will need to update your controller action, LoadTerritoryManagers(), to respond to the ajax request and return a JSON array of {Id,Name} objects.
[HttpPost]
public ActionResult LoadTerritoryManagers(int districtId)
{
var _TMS = (from c in SessionHandler.CurrentContext.ChannelGroups
join cgt in SessionHandler.CurrentContext.ChannelGroupTypes on c.ChannelGroupTypeId equals cgt.ChannelGroupTypeId
where cgt.Name == "Territory" && c.ParentChannelGroupId == districtId
select new TMManager(){ Id = c.ChannelGroupId, Name = c.Name }).OrderBy(m => m.Name);
if (_TMS == null)
return Json(null);
List<TMManager> managers = (List<TMManager>)_TMS.ToList();
return Json(managers);
}
Use the following code. It is used in my project. For Zone and Region I used two drop-down list. On change Zone data I loaded the Region drop-down.
In View page
#Html.DropDownList("ddlZone", new SelectList(#ViewBag.Zone, "Zone_Code", "Zone_Name"), "--Select--", new { #class = "LoginDropDown" })
#Html.DropDownList("ddlRegion", Enumerable.Empty<SelectListItem>(), new { #class = "LoginDropDown" })
The Zone need to load when the view page is load.
In the controller write this method for Region Load
[WebMethod]
public JsonResult LoadRegion(string zoneCode)
{
ArrayList arl = new ArrayList();
RASolarERPData objDal = new RASolarERPData();
List<tbl_Region> region = new List<tbl_Region>();
region = erpDal.RegionByZoneCode(zoneCode);
foreach (tbl_Region rg in region)
{
arl.Add(new { Value = rg.Reg_Code.ToString(), Display = rg.Reg_Name });
}
return new JsonResult { Data = arl };
}
Then use the following JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('#ddlZone').change(function () {
LoadRegion(this.value);
});
function LoadRegion(zoneCode) {
$.ajax({
type: "POST",
url: '#Url.Action("LoadRegion", "RSFSecurity")',
data: "{'zoneCode':'" + zoneCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlRegion').get(0).options.length = 0;
$('#ddlRegion').get(0).options[0] = new Option("--Select--", "0");
$.map(data, function (item) {
$('#ddlRegion').get(0).options[$('#ddlRegion').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Failed to load Item");
}
});
}
});
</script>
We can use the jquery to get and fill the dropdown like this:
<script>
function FillCity() {
var stateId = $('#State').val();
$.ajax({
url: '/Employees/FillCity',
type: "GET",
dataType: "JSON",
data: { State: stateId},
success: function (cities) {
$("#City").html(""); // clear before appending new list
$.each(cities, function (i, city) {
$("#City").append(
$('<option></option>').val(city.CityId).html(city.CityName));
});
}
});
}
</script>
For more detail see
MVC DropDownListFor fill on selection change of another dropdown

Categories

Resources