I'm kinda new at JQuery and are stuck atm. I have an MVC application that draws charts from Google API. I'm working on a UI that alows the user to select a item from a DropDownList, click Run and the charts will load. My current problem is the charts are run directly when i go to the view. The JQuery function that draws the charts implements the GetData ActionResult in GAStatisticsController.
I have a dropDownList with selectable items from a model class and a button ("GAStatisticsReport-Submit"). I just need t check if item "Visitors" is selected in the DropDownList, if that's the case i can click run and the Charts will display the data with visitors. How could i archive this?
The controller has a method called CreateGAStatisticsReport wich returns data to the view for the charts to display. This method has an ActionResult. However when the function draws the charts it draws them from GetData ActionResult and not GAStatistics.
Here is the view:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/GAStatistics/GetData', {}, <--- here's GetData ActionResult in the Controller
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Datum');
tdata.addColumn('number', 'Besökare');
for (var i = 0; i < data.length; i++) {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
var options = {
title: "Number of unique visitors"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));
chart1.draw(tdata, options);
chart2.draw(tdata, options);
chart4.draw(tdata, options);
});
}
</script>
<table class="adminContent">
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.StartDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.StartDate)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.EndDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.EndDate)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.GAStatisticsId ):
</td>
<td class="adminData">
#Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
<input type="button" id="GAStatisticsReport-Submit" class="t-button" value="#T("Run")" />
</tr>
</table>
My ViewModel (note: When SelectListItem "Visitors is selected and the user has clicked the "Run" button it should execute and draw the charts):
public class GAStatisticsListModel : BaseNopModel
{
public GAStatisticsListModel()
{
AvailableGAStatistics = new List<SelectListItem>();
SelectListItem Visitors = new SelectListItem() { Text = "Besökare", Value = "1", Selected = false };
SelectListItem PercentNewVisitors = new SelectListItem() { Text = "Nya Besökare (Procent)", Value = "2", Selected = false };
SelectListItem ConversionRate = new SelectListItem() { Text = "Konverteringsgrad", Value = "3", Selected = false };
AvailableGAStatistics.Add(Visitors);
AvailableGAStatistics.Add(PercentNewVisitors);
AvailableGAStatistics.Add(ConversionRate);
}
[NopResourceDisplayName("Admin.ShopStatistics.List.StartDate")]
[UIHint("DateNullable")]
public DateTime? StartDate { get; set; }
[NopResourceDisplayName("Admin.ShopStatistics.List.EndDate")]
[UIHint("DateNullable")]
public DateTime? EndDate { get; set; }
[NopResourceDisplayName("Admin.GAStatistics.GAStatistics.GAStatisticsList")]
public int GAStatisticsId { get; set; }
public List<SelectListItem> AvailableGAStatistics { get; set; }
}
}
The Controller (GetData passes data to the JQuery code in the view from CreateGAStatisticsReport for the charts to display):
public class GAStatisticsController : Controller
{
//GET: /ShopStatistics/
[HttpPost]
public ActionResult GetData()
{
return Json(CreateGAStatisticsReport(), JsonRequestBehavior.AllowGet);
}
public ActionResult GAStatistics()
{
return View(new GAStatisticsListModel());
}
private List<GAStatistics> CreateGAStatisticsReport()
{
var serviceAccountEmail = "xxxxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"C:\Users\Desktop\NopCommerce\Presentation\Nop.Web\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
// Create the service.
//Twistandtango
var GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
var request = GoogleAnalyticsService.Data.Ga.Get("ga:xxxxxxxx", "2014-01-24", "2014-01-30", "ga:visitors");
//Specify some addition query parameters
request.Dimensions = "ga:date";
request.Sort = "-ga:date";
request.MaxResults = 10000;
//Execute and fetch the results of our query
Google.Apis.Analytics.v3.Data.GaData d = request.Execute();
List<GAStatistics> ListGaVisitors = new List<GAStatistics>();
foreach (var row in d.Rows)
{
GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
ListGaVisitors.Add(GaVisits);
}
return ListGaVisitors;
}
}
For what you want you can't use google.setOnLoadCallback(drawChart) (see this link too understand why). If I understand what you want to do, you must set a event on your button and that event will execute the drawChart() function.
Like this:
$("#GAStatisticsReport-Submit").click(function(){ drawChart() })
So, when you click on that button the chart will be draw.
To draw the chart only if the 'Visitors' is selected you must do something like this:
$("#GAStatisticsReport-Submit").click(function(){
if($("select[name='GAStatisticsId'] option:selected").text()=="Visitors")
drawChart()
})
Related
I implemente dynamic add and remove column it's working fine if I remove last row but if I remove first index then it's losing all other rows.
But if I use FormCollection Its binding but not as array list
public ActionResult Index()
{
var employee = new Employee();
employee.Skills.Insert(0, new Skill());
return View(employee);
}
.cshtml
<table id="skills-table">
<thead>
<tr>
<th style="width:20px;"> </th>
<th style="width:160px;">Skill</th>
<th style="width:150px;">Level</th>
<th style="width:32px;"> </th>
</tr>
</thead>
<tbody>
#for (var j = 0; j < Model.Skills.Count; j++)
{
<tr valign="top">
<th><span class="rownumber"></span></th>
<td>
#Html.TextBoxFor(model => model.Skills[j].Title, new { #class = "skill-title" })
#Html.ValidationMessageFor(model => model.Skills[j].Title)
</td>
<td>
#Html.DropDownListFor(
model => model.Skills[j].Level,
new SelectList(WebApplication4.MetaModels.SkillLevel.GetSkillLevels(), "Code", "Description", Model.Skills[j].Level),
"-- Select --",
new {#class = "skill-level"}
)
#Html.ValidationMessageFor(model => model.Skills[j].Level)
</td>
<td>
#if (j < Model.Skills.Count - 1)
{
<button type="button" class="remove-row" title="Delete row"> </button>
}
else
{
<button type="button" class="new-row" title="New row"> </button>
}
</td>
</tr>
}
</tbody>
</table>
jQuery:
<script type="text/javascript">
var addRow = function () {
addTableRow($("#skills-table"));
return false;
};
var deleteRow = function (event) {
$(event.target).closest("tr").remove();
return false;
};
function addTableRow(table) {
/* Sources:
http://www.simonbingham.me.uk/index.cfm/main/post/uuid/adding-a-row-to-a-table-containing-form-fields-using-jquery-18
http://stackoverflow.com/questions/5104288/adding-validation-with-mvc-3-jquery-validator-in-execution-time
*/
var $ttc = $(table).find("tbody tr:last");
var $tr = $ttc.clone();
$tr.find("input,select").attr("name", function () { // find name in the cloned row
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts from id, including index
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new name
}).attr("id", function () { // change id also
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts
return parts[1] + "_" + ++parts[2] + "__" + parts[3]; // build new id
});
$tr.find("span[data-valmsg-for]").attr("data-valmsg-for", function () { // find validation message
var parts = $(this).attr("data-valmsg-for").match(/(\D+)\[(\d+)]\.(\D+)$/); // extract parts from the referring attribute
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new value
})
$ttc.find(".new-row").attr("class", "remove-row").attr("title", "Delete row").unbind("click").click(deleteRow); // change buttin function
$tr.find(".new-row").click(addRow); // add function to the cloned button
// reset fields in the new row
$tr.find("select").val("");
$tr.find("input[type=text]").val("");
// add cloned row as last row
$(table).find("tbody tr:last").after($tr);
// Find the affected form
var $form = $tr.closest("FORM");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// We could re-validate with changes
// $form.validate($form.data("unobtrusiveValidation").options);
};
(function ($) {
/* Source:
http://www.johnculviner.com/post/2011/11/16/ClearReset-MVC-3-Form-and-Unobtrusive-jQuery-Client-Validation.aspx
*/
$.fn.resetValidation = function () {
var $form = this.closest('form');
//reset jQuery Validate's internals
$form.validate().resetForm();
//reset unobtrusive validation summary, if it exists
$form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul").empty();
//reset unobtrusive field level, if it exists
$form.find("[data-valmsg-replace]")
.removeClass("field-validation-error")
.addClass("field-validation-valid")
.empty();
return $form;
};
})(jQuery);
$(function () {
$(".new-row").click(addRow);
$(".remove-row").click(deleteRow);
})
</script>
Controller:
public ActionResult Index(Employee employee, FormCollection abc, string[]dynamic)
{
return View(employee);
}
Here my FormCollection is getting all the data but not as array type
I have a reservation system in which the date of the reservation is set by DateFrom - DateTo properties range. Now I want to assign the .alert class to those reservations, which are about to expire (1 day to expiration).
The problem is that If a reservation is about to expire, not only this reservation has .alert class set but also all other reservations, so all <tr> are red even though only one is supposed to. How to bind It only to current reservation?
Condition
foreach(Reservation r in res)
{
bool varovani;
if (r.DateTo.AddDays(-1).Day <= DateTime.Now.Day)
{
varovani = true;
}
else
{
varovani = false;
}
ViewBag.Varovani = varovani;
}
Table in View
<tbody>
#foreach (Reservation r in Model)
{
string alertClass = "";
if (ViewBag.Varovani == true)
{
alertClass = "danger";
}
else
{
alertClass = "";
}
<tr class="#alertClass">
<td>#r.Reserved.Id</td>
<td>#r.Name</td>
<td>#r.DateFrom</td>
<td>#r.DateTo</td>
<td>
#Ajax.ActionLink("Detail", "Detail", "Skies", new { id = r.Reserved.Id }, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "modalContent", OnBegin = "openModalWindow" })
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Reservation", new { id = r.Id }, null)
#Html.ActionLink("Delete", "Delete", "Reservation", new { id = r.Id }, new { onclick = "return confirm('Přejete si opravdu smazat tuto výpujčku? " + r.Name + "');" })
</td>
</tr>
}
</tbody>
The reason this is happening is because ViewBag.Varovani is a single bool value. So every time you iterate through you overwrite the "Varovani" bool value. What you want to do is add a property to you Reservation class:
public class Reservation
{
//Rest of class
public bool Varovani => DateTo.AddDays(-1).Day <= DateTime.Now.Day;
}
Then in your view:
<tbody>
#foreach (Reservation r in Model)
{
<tr class="#(r.Varovani ? "danger" : "")">
<td>#r.Reserved.Id</td>
<td>#r.Name</td>
<td>#r.DateFrom</td>
<td>#r.DateTo</td>
<td>
#Ajax.ActionLink("Detail", "Detail", "Skies", new { id = r.Reserved.Id }, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "modalContent", OnBegin = "openModalWindow" })
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Reservation", new { id = r.Id }, null)
#Html.ActionLink("Delete", "Delete", "Reservation", new { id = r.Id }, new { onclick = "return confirm('Přejete si opravdu smazat tuto výpujčku? " + r.Name + "');" })
</td>
</tr>
}
</tbody>
Alternatively you could perform the logic in your view (although I would not recommend it unless you cannot modify the Reservation class):
#foreach (Reservation r in Model)
{
string alertClass = "";
if (r.DateTo.AddDays(-1).Day <= DateTime.Now.Day)
{
alertClass = "danger";
}
else
{
alertClass = "";
}
//Rest of your original Razor
Disclaimer
I have no idea what "Varovani" means, so only use that as your property name if it describes your logic properly.
I have a .Net Core application and in one of my views I want to have a Google Map in which I want to be able to draw dynamical polylines.
Index.cshtml
I have included a Google Map on my view as follows:
<div class="col-md-6 col-lg-6">
<h3>My Google Maps Demo</h3>
<div id="map"></div>
</div>
<script>
function initMap() {
var center = { lat: 55.92965249, lng: 12.47840507 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: uluru
});
$.get()
$.post()
route.setMap(map);
}
</script>
And in my _Layout.cshtml I have:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=...api key...&callback=initMap">
</script>
All of this works as intended, but I am unsure of whether this is the proper way to show Google Maps in a .Net Core application?
Furthermore I want to be able to draw dynamical routes in my Google Maps implementation. This is done via the following code
var route = new google.maps.Polyline({
path: routeCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
where routeCoordinates is a list of coordinates:
var routeCoordinates = [
{lat: 55.92965249, lng: 12.47840507},
{lat: 55.92941392, lng: 12.47832253},
{lat: 55.92918626, lng: 12.47824027},
...
{lat: 55.91474539, lng: 12.47145191},
{lat: 55.91450191, lng: 12.47139283},
{lat: 55.91425197, lng: 12.47134614}
]
All the above is of course done statically in my Index.cshtml.
So is there a better way to do this? And how would I go about adding and removing lines dynamically (hopefully) by using my Controller? I expect something like:
public async Task<IActionResult> Index()
{
return View(await _context.Trips.ToListAsync());
//context is my db
}
Right now it is not present but I will be getting a list of coordinates from my context through my EF implementation.
EDIT:
Since I posted this I have continued a bit, and I now have a PartialView that I want to load when clicking a table row:
MapPartialView.cshtml
#model IEnumerable<LngLat>
<div class="col-md-6 col-lg-6">
<h3>My Google Maps Demo</h3>
<div id="map"></div>
</div>
<script>
function initMap() {
var center = { lat: 55.92965249, lng: 12.47840507 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: center
});
//$.get();
//$.post();
routeCoordinates = #Model;
var route = new google.maps.Polyline({
path: routeCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
route.setMap(map);
}
</script>
And my:
Index.cshtml
// table header and so forth..
<tbody>
#foreach (var item in Model)
{
<tr class="trips" data-id="#item.TripID" data-url="#Url.Action("ExpandMap", "Trip")">
<td>
#Html.DisplayFor(modelItem => item.DeviceID)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.Duration)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartLocation)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndLocation)
</td>
</tr>
}
</tbody>
<div id="partialMap"></div>
And in my:
site.js
$('.trips').each(function (i, e) {
var _this = $(this);
var element = $(e).children('td');
element.click(function () {
//console.log("Clicked! " + _this.data('url') + " " + _this.data('id'));
$("#partialMap").load(_this.data('url'), { id: _this.data('id') }, function () {
$("#partialMap").slideDown('200');
});
});
});
And lastly my controller and the ExpandMap function:
TripController.cs
public IActionResult ExpandMap(int id)
{
var trip = _context.Trips.SingleOrDefault(t => t.TripID == id);
List<LngLat> routeCoordinates = new List<LngLat>
{
new LngLat() { lat = 55.92965249, lng = 12.47840507},
new LngLat() { lat = 55.92941392, lng = 12.47832253},
...
new LngLat() { lat = 55.91450191, lng = 12.47139283},
new LngLat() { lat = 55.91425197, lng = 12.47134614}
};
string routeCoordinatesJS = JsonConvert.SerializeObject(routeCoordinates, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return PartialView("MapPartialView", routeCoordinatesJS);
}
But when I run the code I get a:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
You can export your context to a list of lat and lng
public class LngLat
{
public double lat { get; set; }
public double lng { get; set; }
}
The build your list with data from your db and send it to the View():
public async Task<IActionResult> Index()
{
List<LngLat> routeCoordinates = await _context.Trips.Select(c=> new LngLat {lat = c.latitude, lng = c.longitude })
//Serialize your routeCoordiamte with Json.Net
string routeCoordinatesJs = JsonConvert.SerializeObject(routeCoordinates, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
return View(routeCoordinatesJs);
}
In your View():
var routeCoordinates = #Model
I am newbie in asp.net mvc.
I have 2 cascading dropdownlist and 1 file input on my page.
I made cascading dropdownlists following this tutorial. But when I trying to pass value to controller, there is an error System.ArgumentException, null parameter. I looked up the list of parameters using Firebug, but I can't find value of second dropdown at all.
My controller code is below:
public ActionResult Index()
{
List<SelectListItem> branchNames = new List<SelectListItem>();
FormatModel fmtModel = new FormatModel();
List<branch> branches = db.branch.ToList();
branches.ForEach(x =>
{
branchNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
fmtModel.BranchNames = branchNames;
return View(fmtModel);
}
[HttpPost]
public ActionResult GetPaymentSystem(string branchId)
{
int intBranchId;
List<SelectListItem> paymentSystemNames = new List<SelectListItem>();
if (!string.IsNullOrEmpty(branchId))
{
intBranchId = Convert.ToInt32(branchId);
List<paymentSysDTO> paymentSystems =
(from ps in db.paymentSys
join ps_br in db.br_ps_format on ps.id equals ps_br.ps_id
join br in db.branch on ps_br.branch_id equals br.id
where br.id == intBranchId
select new paymentSysDTO
{
id = ps.id,
name = ps.name,
code = ps.code
}
).ToList();
paymentSystems.ForEach(x =>
{
paymentSystemNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
}
return Json(paymentSystemNames, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Index(int BranchNames, int PaymentSystemNames, HttpPostedFileBase file)
{
//controller code
}
View code:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<legend>Введите данные:</legend>
<table>
<tr>
<td>
<label>Филиал</label>
</td>
<td>
#Html.DropDownListFor(x => x.BranchNames, Model.BranchNames, "Выбрать", new { id = "ddlBranch" })
</td>
</tr>
<tr>
<td>
<label>Платежная система/Банк</label>
</td>
<td id="PaymentSystem">
#Html.DropDownListFor(x => x.PaymentSystemNames, new List<SelectListItem>(), "Выбрать", new { #id = "ddlPaymentSystem" })
</td>
</tr>
<tr>
<td>
<input id="InputFile" type="file" name="file" />
</td>
</tr>
<tr>
<td>
<input id="ConvertButton" type="submit" value="Конвертировать" />
</td>
</tr>
</table>
}
#if (null != TempData["msg"])
{
#Html.Raw(TempData["msg"])
}
<script type="text/javascript">
$(function () {
$('#ddlBranch').change(function () {
$.ajax({
type: 'POST',
url: "/Home/GetPaymentSystem",
data: { branchID: $('#ddlBranch').val() },
datatype: "json",
traditional: true,
success: function (data) {
var paymentSystem = "<select id='ddlPaymentSystem'>";
paymentSystem = paymentSystem + '<option value ="">Select</option>';
for (var i = 0; i < data.length; i++)
{
paymentSystem = paymentSystem + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
paymentSystem = paymentSystem + '</select>';
$('#PaymentSystem').html(paymentSystem);
}
cas
});
});
});
</script>
Sorry for my English and thanks for ur help.
I have three dropdownlist - Project, Sprint, Story.
Sprint dropdownlist will be binded on the basis of selected Project, Story dropdownlist will be binded on the basis of selected Sprint. On the basis of selected Story, i want to show a webgrid.
what i m doing is:
my Project dropdownlist is on the main view page, Sprint dropdownlist, and Story dropdownlist are two diferent partial views. When i select from Project, selected value is taken in jquery and passed to controller as:
$('#Project').change(function (e) {
e.preventDefault();
var selectedVal = $("#Project").val();
$.ajax({
url: "/Task/BindSprintList",
data: { projectTitle: selectedVal },
type: 'Get',
success: function (result) {
$('#ViewGrid').html(result);
},
error: function () {
alert("something seems wrong");
}
});
});
Now Sprint Dropdown list appears. When i select from Sprint, selected value is taken in jquery and passed to controller as:
$('#Sprint').change(function (e) {
e.preventDefault();
var selectedProjectVal = $("#Project").val();
var selectedSprintVal = $("#Sprint").val();
$.ajax({
url: "/Task/BindStoryList",
data: { projectTitle: selectedProjectVal, sprintTitle: selectedSprintVal },
type: 'Get',
success: function (result) {
$('#ddlStory').html(result); },
error: function (err) {
alert("something seems wrong "+ err);
}
});
});
but now Story Dropdownlist is not displaying.
MainPage.cshtml
<table>
#{
if (ViewBag.ProjectList != null)
{
<tr>
<td>
<h4>SELECT PROJECT </h4>
</td>
<td>
#Html.DropDownList("Project", new SelectList(ViewBag.ProjectList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
}
if (ViewBag.SprintList != null)
{
Html.RenderPartial("PartialSprintDropDown", Model.AsEnumerable());
}
if (ViewBag.StoryList != null)
{
Html.RenderPartial("PartialStoryDropDown", Model.AsEnumerable());
}
}
</table>
PartialSprintDropDown.cshtml
<table>
<tr>
<td>
<h4>SELECT SPRINT</h4>
</td>
<td>
#Html.DropDownList("Sprint", new SelectList(ViewBag.SprintList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
</table>
<script src="~/Script/Task/IndexTask.js" type="text/javascript"></script>
PartialStoryDropDown.cshtml
<div id="ddlStory">
<table>
<tr>
<td>
<h4>SELECT STORY</h4>
</td>
<td>
#Html.DropDownList("Story", new SelectList(ViewBag.StoryList, "Value", "Text"), " -- Select -- ")
</td>
</tr>
</table>
</div>
<script src="~/Script/Task/IndexTask.js" type="text/javascript"></script>
Can anyone suggest me that why Story DropdownList is not displaying. Even when i m debbuging PartialStoryDropDown.cshtml, "ViewBag.StoryList" contains data as expected, but not showing on the page.
I m containing my data in Viewbag.SprintList and Viewbag.StoryList.
SprintDropdownlist is displaying.
How to resolve this ?
BindSprintList()
public ActionResult BindSprintList(string projectTitle)
{
try
{
string Owner = Session["UserName"].ToString();
int? ProjectId = GetProjectID(projectTitle);
var ddlSprint = new List<string>();
List<SelectListItem> items = new List<SelectListItem>();
var querySprint = (from sp in entities.Sprints
where sp.Project_ID == ProjectId && sp.Sprint_Status != "Completed"
select sp).ToList();
foreach (var item in querySprint.ToList())
{
SelectListItem li = new SelectListItem
{
Value = item.Sprint_Title,
Text = item.Sprint_Title
};
items.Add(li);
}
IEnumerable<SelectListItem> List = items;
ViewBag.SprintList = new SelectList(List, "Value", "Text");
}
catch (Exception e)
{
var sw = new System.IO.StreamWriter(filename, true);
sw.WriteLine("Date :: " + DateTime.Now.ToString());
sw.WriteLine("Location :: AgileMVC >> Controllers >> TaskController.cs >> public ActionResult BindSprintList(string projectTitle)");
sw.WriteLine("Message :: " + e.Message);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
return PartialView("PartialSprintDropDown", ViewBag.SprintList);
}
BindStoryList()
public ActionResult BindStoryList(string projectTitle, string sprintTitle)
{
try
{
string Owner = Session["UserName"].ToString();
int? ProjectId = GetProjectID(projectTitle);
int? SprintId = GetSprintID(ProjectId, sprintTitle);
var ddlStory = new List<string>();
List<SelectListItem> items = new List<SelectListItem>();
var queryStory = (from st in entities.Stories
join spss in entities.SprintStories on st.Story_ID equals spss.Story_ID
where spss.Sprint_ID == SprintId && spss.Project_ID == ProjectId
select st).ToList();
foreach (var item in queryStory.ToList())
{
SelectListItem li = new SelectListItem
{
Value = item.Story_Title,
Text = item.Story_Title
};
items.Add(li);
}
IEnumerable<SelectListItem> List = items;
ViewBag.StoryList = new SelectList(List, "Value", "Text");
}
catch (Exception e)
{
var sw = new System.IO.StreamWriter(filename, true);
sw.WriteLine("Date :: " + DateTime.Now.ToString());
sw.WriteLine("Location :: AgileMVC >> Controllers >> TaskController.cs >> public ActionResult BindStoryList()");
sw.WriteLine("Message :: " + e.Message);
sw.WriteLine(Environment.NewLine);
sw.Close();
}
return PartialView("PartialStoryDropDown", ViewBag.StoryList);
}
I think I see your problem - ddlStory div comes as part of result. So when you say $('#ddlStory'), it doesn't do anything since its not on the page yet.
I think in your main page, you need to have a placeholder for ddlStory and replace that placeholder's html. Something like $('#ddlStoryWrapper').html(result) where ddlStoryWrapper is just an empty div on the page.