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.
Related
I am trying to get data in my DataTable by ID, the data row coming from SQL Server to my controller but I am confused: how to pass this data to my DataTable in view?
I am using this code - my model:
public class EmployeesModel
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Position { get; set; }
public string Office { get; set; }
[Required(ErrorMessage ="Please enter date")]
public DateTime HiringDate { get; set; }
public int Salary { get; set; }
}
My controller
public JsonResult GetEmpByID(int id)
{
List<EmployeesModel> employeeList = new List<EmployeesModel>();
string CS = ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_GetEmpByID", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpID", SqlDbType.NVarChar).Value = id; //Added Parameter
conn.Open();
// Get
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EmployeesModel employee = new EmployeesModel();
employee.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
employee.Name = reader["Name"].ToString();
employee.Gender = reader["Gender"].ToString();
employee.Age = Convert.ToInt32(reader["Age"]);
employee.Position = reader["Position"].ToString();
employee.Office = reader["Office"].ToString();
employee.HiringDate = Convert.ToDateTime(reader["HiringDate"]);
employee.Salary = Convert.ToInt32(reader["Salary"]);
employeeList.Add(employee);
}
}
//return View(employeeList); Commented out
//return RedirectToAction("GetEmpByID"); Commented out
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
}
My view
#model IEnumerable<SQLWithoutEF.EmployeesModel>
<input type="text" id="tablename" /> //Here I enter Employee ID and below is button
<asp:Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#tablename').val())">Get Data By ID</asp:Button>
#*Data Table ==============*#
<table class="table table-bordered table-responsive table-hover" id="MyTable">
<thead>
<tr>
<th style="display:none">#Html.DisplayNameFor(m => m.EmployeeId)</th>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.Gender)</th>
<th>#Html.DisplayNameFor(m => m.Age)</th>
<th>#Html.DisplayNameFor(m => m.Position)</th>
<th>#Html.DisplayNameFor(m => m.Office)</th>
<th>#Html.DisplayNameFor(m => m.HiringDate)</th>
<th>#Html.DisplayNameFor(m => m.Salary)</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var employee1 in Model)
{
<tr>
<td style="display:none">#employee1.EmployeeId</td>
<td>#employee1.Name</td>
<td>#employee1.Gender</td>
<td>#employee1.Age</td>
<td>#employee1.Position</td>
<td>#employee1.Office</td>
<td>
#if (employee1.HiringDate != null)
{
#employee1.HiringDate
}
</td>
<td>#employee1.Salary</td>
<td>
<asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> |
<asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button>
</td>
</tr>
}
</tbody>
</table>
My jQuery / Ajax - here I need help:
function GetByName(id) {
if (confirm("Are You Sure to Get " + id + " " + " ?")) {
$('#MyTable tbody tr').remove();
$.ajax({
type: "GET",
url: '/Home/GetEmpByID?id=' + id,
//data: JSON.stringify({ id: id }),
//contentType: application/json, charset: utf-8,
processData: false,
dataType: 'json',
bprocessing: true,
success: function (data) { // Till here data coming but it's not working further
var items = '';
$.each(data, function (item) {
debugger;
var rows = '';
for (var i = 0; i < item.length[0]; i++) {
rows = "<tr><td>" + data + "</td>"
+ '<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button></td>'
"</tr>";
$('#MyTable tbody').append(rows);
}
})
},
}).catch(function (xhr, status, error) {
var errorMeassage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMeassage);
})
};
};
Here is the screenshot what output I am getting
enter image description here
Kindly suggest how I can send data from my controller to my DataTable using Ajax?
Thanks
From the controller API action,
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
It will return the response with body as an object with data property which contains the array, instead of the response is the array.
The response body would be as:
{
data: [/* Employee List */]
}
In JavaScript part, to take the employee array
var items = data.data;
The implementation in success callback should be:
var items = data.data;
$.each(items, function (index, item) {
debugger;
var rows = '';
rows = `<tr>
<td style="display:none">${item.EmployeeId}</td>
<td>${item.Name}</td>
<td>${item.Gender}</td>
<td>${item.Age}</td>
<td>${item.Position}</td>
<td>${item.Office}</td>
<td>${item.HiringDate}
</td>
<td>${item.Salary}</td>
<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="${item.Name}" id="deletebtn" onclick="deleteF(${item.EmployeeId}">DeleteEmp</asp:button></td>
</tr>`;
$('#MyTable tbody').append(rows);
})
Note: You may use the string interpolation / template literal which makes it easier to build the template string.
Demo
This is my controller.
public class DokuzasController : Controller
{
public ActionResult AddOrEdit()
{
DersViewModel model = new DersViewModel();
schoolEntities sc = new schoolEntities();
List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();
model.DersList = (from s in dersList
select new SelectListItem
{
Text = s.Ders1,
Value = s.DersID.ToString()
}).ToList();
model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel model)
{
if (model.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
TempData["SuccessMessage"] = "Saved.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
TempData["SuccessMessage"] = "Successful.";
}
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult SaatList(int id)
{
schoolEntities sc = new schoolEntities();
List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
List<SelectListItem> itemList = (from i in saatList
select
new SelectListItem
{
Value = i.SaatID.ToString(),
Text = i.Saat1
}).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
}
And this is my AddOrEdit file.
#model Mvc.Models.DersViewModel
#{
ViewBag.Title = "AddOrEdit";
}
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
#Html.DropDownListFor(m => m.SaatID, Model.SaatList)
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#DersID").change(function () {
var id = $(this).val();
var saatList = $("#SaatID");
saatList.empty();
$.ajax({
url: '/Dokuzas/SaatList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
saatList.append('<option value=' + option.Value + '>'
+ option.Text + '</option>')
});
}
});
});
});
</script>
}
I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?
in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownList("DersID", Model.DersList as SelectList)
<select name="id" id="SaatID" data-url="#Url.Action("SaatList","Home")">
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
<script type="text/javascript">
$(function(){
$("#DersID").change(function (e) {
var $SaatID = $("#SaatID");
var url = $SaatID.data("url")+'?id='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>
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.
[HttpPost]
public ActionResult Charter(List<int> stateIds)
{
try
{
if (!stateIds.Any())
{
return Json("State list is empty", JsonRequestBehavior.AllowGet);
}
var states = new List<CfVersionEntities.Model.State>();
stateIds.ForEach(id =>
{
using (var db = new Storage_cfEntities())
{
var stateList = db.States.Where(i => i.Id == id).ToList();//get names of states with matching id and save in array named
if (!stateList.Any()) return;
var state = stateList[0];
states.Add(state);
}
});
return !states.Any() ? Json(new List<State>(), JsonRequestBehavior.AllowGet) : Json(states, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(new List<State>(),
JsonRequestBehavior.AllowGet);
}
}
I have a method that accepts values from my jquery scripts which is below, the script works fine and sends the values, the values are received in my method, i have confirmed that. but when i run it i get the error :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.... I am using the values from my jquery to loop through my database and select rows that have corresponding IDs, i am then sending this result back to another function in my jquery which creates a highchart with the values
This is my View which includes my script.
List Of States
<p>
<h2> #Html.ActionLink("Add A New State", "CreateState")</h2>
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Stations)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stations)
</td>
<td>
#Html.ActionLink("Update Stations", "UpdateStation", new {id = item.Id})||
<div>
<input type="checkbox" id="#item.Id" value="#item.Id" class="chk" onclick="setChecked(this)"> <label >Add to Chart</label>
</div>
</td>
</tr>
}
</table>
<div id="charts" style="width:100%" height="400px;"></div>
<input type="button" value="Verify Selections" onclick="submit()"/>
<input type="button" value ="View Chart" onclick="location.href='#Url.Action("Charter")'" />
<script type="text/javascript">
var collection = [];
function setChecked(el) {
var id = $(el).attr('id');
if ($(el).is(':checked'))
{
collection.push(id);
} else {
$.each(collection, function (item, index)
{
if (item === id)
{
collection.splice(index, 1);
}
});
}
}
function submit() {
if (collection == null || collection.length < 1) {
alert('please select at least one state.');
return;
}
$.ajax({
type: "POST",
url: '/State/Charter',
data: { stateIds: collection },
dataType: 'application/json',
success: function (response)
{
if (response.length > 0) {
designChart(response);
}
}
});
}
function designChart(response)
{
var names = [];
var stations = [];
$.each(response, function (item) {
if (item.Id > 0) {
names.push(item.Name);
stations.push(item.Stations);
}
});
$("#charts").highcharts({
chart:
{
type: 'line'
},
title: {
text: 'States'
},
xAxis: {
categories: names
},
yAxis:
{
title:
{
text: 'Stations',
categories: stations
}
}
});
}
</script>
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.