I have dropdown list in my view
#Html.DropDownList("Question1", null, "Вопрос 1", htmlAttributes: new {#class = "form-control", #style = "height:40px;margin-bottom: 20px;"})
I have AJAX call that display all questions
Here it is
function question_update() {
$(".count").empty();
$.ajax({
url: '#Url.Action("QuestionsList", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var email = result;
var edit = '#Url.Content("~/Images/Edit.png")';
var delete_ = '#Url.Content("~/Images/Delete.png")';
// console.log(result[0].Name);
for (var i = 0; i <= email.length - 1; i++) {
var arrow = '#Url.Content("~/Images/plus_plus.png")';
var questionHtml = '<div class = "title" style="margin-top:15px;margin-left:15px;margin-bottom:10px;">'
+
'<img class="click" src="'
+ arrow
+ '">' +
'<span class="test">' +
'<input type="text" class="testclass" readonly value="' +
result[i].Quest + '">' +
'<a style="margin-left:25px;">' +
'<img src="' + edit + '"/>' +
'<img style="margin-left:10px;" src="' + delete_ + '"/>' +
'</div>' +
'<div class ="content" style="margin-left:60px; width: 80%; height: 100px; background: white;">' +
'<div style="width: 100%">' +
'<div style="float:left; width: 50%;">' +
'<b style="margin-left: 40px;">' + "Время на ответ" + '</b>' +
'<b>' + ":" + '</b>' +
'<span>' + "Время на подготовку" +'</span>'+
'</div>' +
'<div style="float:right; width: 50%;">' +
'<b>' + result[i].TimeForAnswer + '</b>' +
'<b>' + ":" + '</b>' +
'<b>' + result[i].TimeForReady + '</b>'+
'</div>' +
'</div>' +
'</div>';
$(".count").append(questionHtml);
At sucess of it I need to update values in dropdown
I make it like this
function question_update() {
$(".count").empty();
$.ajax({
url: '#Url.Action("QuestionsList", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var email = result;
var edit = '#Url.Content("~/Images/Edit.png")';
var delete_ = '#Url.Content("~/Images/Delete.png")';
// console.log(result[0].Name);
for (var i = 0; i <= email.length - 1; i++) {
var arrow = '#Url.Content("~/Images/plus_plus.png")';
var questionHtml = '<div class = "title" style="margin-top:15px;margin-left:15px;margin-bottom:10px;">'
+
'<img class="click" src="'
+ arrow
+ '">' +
'<span class="test">' +
'<input type="text" class="testclass" readonly value="' +
result[i].Quest + '">' +
'<a style="margin-left:25px;">' +
'<img src="' + edit + '"/>' +
'<img style="margin-left:10px;" src="' + delete_ + '"/>' +
'</div>' +
'<div class ="content" style="margin-left:60px; width: 80%; height: 100px; background: white;">' +
'<div style="width: 100%">' +
'<div style="float:left; width: 50%;">' +
'<b style="margin-left: 40px;">' + "Время на ответ" + '</b>' +
'<b>' + ":" + '</b>' +
'<span>' + "Время на подготовку" +'</span>'+
'</div>' +
'<div style="float:right; width: 50%;">' +
'<b>' + result[i].TimeForAnswer + '</b>' +
'<b>' + ":" + '</b>' +
'<b>' + result[i].TimeForReady + '</b>'+
'</div>' +
'</div>' +
'</div>';
$(".count").append(questionHtml);
$.ajax({
url: '#Url.Action(" QuestionsList_new", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var $vacancy = $("#Question1");
$vacancy.empty();
$.each(result, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
}
});
}
}
});
}
But I don't see any updates in DropdownList.
Where is my problem?
UPDATE
All okay. But I have new problem. In my dropdownlist I have undefined.
<select class="form-control" id="Question1" name="Question1" style="height:40px;margin-bottom: 20px;"><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option></select>
How I can solve this?
Based on the sample data you gave for the result variable coming back from the server:
{ ID = 1048, Quest = "тест" }
your .each loop needs to look like this:
$.each(result, function (a, b) {
$vacancy.append('<option value="' + b.ID + '">' + b.Quest + '</option>');
});
The properties "text" and "value" that you were trying to access don't exist in the data, hence why you were getting "undefined". You need to use the names of the actual properties involved.
Related
I'm trying to load partial view as Json object using Ajax. I have a dropdown select list items, for each time I click on the item in the dropdown list the data must be returned respectively.
Here is my NotePartial.cs action that return partial view as Json.
[ActionName("NotePartial")]
public JsonResult NotePartial(int? id)
{
if (id == null)
return null;
var noticeModel = _context.Course
.Include(n => n.Notices)
.AsNoTracking()
.FirstOrDefault(m => m.CourseId == id);
if (noticeModel == null)
return null;
return Json(noticeModel);
}
This is my .cshtml file which will render and load Json as partial view.
<div class="col-sm-4 offset-4 form-inline">
<label class="">Courses </label>
<select id="courses_dropdown_list" class="custom-select ml-2" asp-items="#(new
SelectList(ViewBag.CourseList, "Value","Text") )">
</select>
// some code ...
<div class="note-partial">
<section class="text-center">
<div class="container">
<div class="row" id="note_table" data-url="#Url.Action(action: "NotePartial", controller: "Note")">
// I want partial view is loaded in here
</div>
</div>
</section>
</div>
And this is my Ajax script
#section Scripts
{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$(document).ready(function () {
$("#courses_dropdown_list").change(function () {
var id = $("#courses_dropdown_list").val();
var note_db = $("#note_table");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("NotePartial", "Note")',
data: { "id": id },
success: function (data) {
var result = "";
note_db.html('');
$.each(data, function (id, note) {
result += '<table class="table table-striped">' +
'<thead>' +
'<tr>' +
'<th>#</th>' +
'<th>Name</th>' +
'<th>File Type</th>' +
'<th>File</th>' +
'<th>Created On</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr>' +
'<td>' + note.Id + '</td>' +
'<td>' +
'<a class="nav-link" mt-0 asp-controller="Note" asp-action="Detail" asp-route-Id="">' + note.Name + '</a>' +
'</td>' +
'<td>' +
'<a>' + note.FileType +'</a>'
'</td>' +
'<td>' +
'<a class="nav-link mt-0" asp-controller="Note" asp-action="Detail" asp-route-Id="">' + '##' + '</a>' +
'</td>'
'<td>' + note.CreatedOn +'</td>' +
'</tr>'
'</tbody>';
});
note_db.html(result);
},
error: function (xhr, ajaxOtions, errorMsg) {
alert("Failed to retrive data");
}
})
});
});
</script>
When I ran the program and set break points for NoteParial action, it retured the object as I expected brefore and the Ajax request is succeced as well. However the partial view is not displaying in the div tag. Hope someone could help me!
You need to move the result variable before ajax call.
#section Scripts
{
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$(document).ready(function () {
$("#courses_dropdown_list").change(function () {
var id = $("#courses_dropdown_list").val();
var note_db = $("#note_table");
// **** Move result variable to here
var result = "";
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("NotePartial", "Note")',
data: { "id": id },
success: function (data) {
note_db.html('');
$.each(data, function (id, note) {
result += '<table class="table table-striped">' +
'<thead>' +
'<tr>' +
'<th>#</th>' +
'<th>Name</th>' +
'<th>File Type</th>' +
'<th>File</th>' +
'<th>Created On</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr>' +
'<td>' + note.Id + '</td>' +
'<td>' +
'<a class="nav-link" mt-0 asp-controller="Note" asp-action="Detail" asp-route-Id="">' + note.Name + '</a>' +
'</td>' +
'<td>' +
'<a>' + note.FileType +'</a>'
'</td>' +
'<td>' +
'<a class="nav-link mt-0" asp-controller="Note" asp-action="Detail" asp-route-Id="">' + '##' + '</a>' +
'</td>'
'<td>' + note.CreatedOn +'</td>' +
'</tr>'
'</tbody>';
});
note_db.html(result);
},
error: function (xhr, ajaxOtions, errorMsg) {
alert("Failed to retrive data");
}
})
});
});
</script>
I'm generating a table usinf jQuery. in each row I have an input field, that should search some values from DB usibg autocomplete. first row works perfectley but with the second I have problems, it returns in autocomplete only a value from the field above, I have no idea how can i fix it... can somebody help?
here is my code:
$.ajax({
type: "GET",
url: "/Home/JsonWeekEvents",
dataType: "JSON",
success: function (result) {
$.each(result, function (i, val) {
var trow = $('<tr/>').data("id", val.Id);
//trow.append('<td>' + val.Id + " " + '</td>');
trow.append('<td style="padding:5px; width:100px; height:70px"></td>');
trow.append('<td valign="top" style="padding:2px; width:150px; height:100px">' +
'<div class="ui-widget">' +
'<input size="10" maxlength="10" id="tagsM" class="tags" />' +
'<input type="button" id="addBtn" onclick="addEvent();" size="5" value="+" /><br/>' +
'<div style="text-align:center" id="desc_Num">' + val.Monday + '</div >' +
'</div >' +
'</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#weekEvents").html(tab);
},
error: function () {
alert("Failed! Please try again.");
}
});
var tab = $('<table class=MyTable border=1 ></table>');
var thead = $('<thead></thead>');
thead.append('<th style="padding:5px">FSE' + " " + '</th>');
thead.append('<th style="padding:5px">Monday' + " " + '</th>');
thead.append('<th style="padding:5px">Tuesday' + " " + '</th>');
thead.append('<th style="padding:5px">Wednesday' + " " + '</th>');
thead.append('<th style="padding:5px">Thursday' + " " + '</th>');
thead.append('<th style="padding:5px">Friday' + " " + '</th>');
thead.append('<th style="padding:5px">Saturday' + " " + '</th>');
thead.append('<th style="padding:5px">Sunday' + " " + '</th>');
tab.append(thead);
tab.on("focus", "input[class='tags']", function (e) {
//var prefix = $('.tags').val();
$('.tags').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/GetSearchValue",
dataType: "json",
data: { search: $('.tags').val() },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Title + ', ' + item.Description, value: item.Title,
Id: item.Id,
Title: item.Title,
Description: item.Description,
Location: item.Location
}
}));
},
error: function (xhr, status, error) {
alert("Error!" + xhr);
},
});
}
});
Would advise something like the following:
tab.on("focus", "input[class='tags']", function(e) {
if (!$(this).hasClass("ui-autocomplete")) {
$(this).autocomplete({
source: function(request, response) {
$.getJSON("/Home/GetSearchValue", {
search: request.term
},
function(data) {
response($.map(data, function(item) {
return {
label: item.Title + ', ' + item.Description,
value: item.Title,
Id: item.Id,
Title: item.Title,
Description: item.Description,
Location: item.Location
}
}));
});
}
});
}
});
This will initialize autocomplete on focus event. If it's already initialized, that will not be repeated. The source will perform a GET request and search for the request.term from the User's input on that specific field.
I want to get dropdownlist in every row when addrow button hits.
I don't know how to do it.
Here what I have:
$('#addrow').click(function () {
var tr = "<tr><td>##Html.DropDownList(\"Bank\", null, htmlAttributes: new { ##class = \"form-control\" })"
+ "</td><td><div>"
+ "<div class=\"input-group date\">"
+ "<div class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i>"
+ "</div>"
+ "<input type=\"text\" class=\"form-control ChqDate\" name=\"ChqDate\" placeholder=\"Chq Date\">"
+ "</div><!-- /.input group -->"
+ "</div></td>"
+ "<td><input type=\"number\" name=\"Amount\" class=\"form-control\" id=\"ChqAmount\" placeholder=\"Cheque Amount\" /></td>"
+ "<td><button data-itemId=\"0\" type=\"button\" class=\"btn btn-danger removeRow\"><span class=\"glyphicon glyphicon-trash\"></span></button></td></tr>";
$('#example1 tbody').append(tr);
$('#example1 tbody .ChqDate').datepicker({
autoclose: true
});
});
first make your dropdown in view (but invisible to user):
#Html.DropDownList("Bank-Template", null, htmlAttributes: new { style="display: none;", id="Bank-Template" })
and then in javascript use it as template:
$('#addrow').click(function () {
var tr = "<tr><td><select name=\"Bank\" class=\"form-control\">" + $("#Bank-Template").html()
+ "</select></td><td><div>"
+ "<div class=\"input-group date\">"
+ "<div class=\"input-group-addon\"><i class=\"fa fa-calendar\"></i>"
+ "</div>"
+ "<input type=\"text\" class=\"form-control ChqDate\" name=\"ChqDate\" placeholder=\"Chq Date\">"
+ "</div><!-- /.input group -->"
+ "</div></td>"
+ "<td><input type=\"number\" name=\"Amount\" class=\"form-control\" id=\"ChqAmount\" placeholder=\"Cheque Amount\" /></td>"
+ "<td><button data-itemId=\"0\" type=\"button\" class=\"btn btn-danger removeRow\"><span class=\"glyphicon glyphicon-trash\"></span></button></td></tr>";
$('#example1 tbody').append(tr);
$('#example1 tbody .ChqDate').datepicker({
autoclose: true
});
});
but you must set unique name for controls, or data may post to server as array. for example ChqDate[0], Bank[0],ChqDate[1], Bank[1],...
I want to pass value through jQuery Json.The problem is that while passing the value then,it have some problem,thats why it is not calling c# code.
This is the html table:
$(function ()
{
debugger
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm7.aspx/BindCategoryDatatable",
data: "{}",
dataType: "json",
success: function (dt) {
debugger;
for (var i = 0; i < dt.d.length; i++) {
$("#tblid > tbody").append("<tr><td> <input type='checkbox' class='chk' id=" + dt.d[i].projectid + " /></td><td>" + dt.d[i].projectname + "</td><td>" + dt.d[i].Name + "</td><td>" + dt.d[i].technology + "</td><td>" + dt.d[i].projectliveurl + "</td><td><input type='image' src=" + dt.d[i].StatusImage + " onclick='actvstatus(" + dt.d[i].projectid + ", " + dt.d[i].status + ")' alt='Submit' width='18' height='18'> </td><td>" + dt.d[i].DisplayOrder + "</td><td> <i class='ui-tooltip fa fa-pencil' onclick='btnQueryString_Click(" + dt.d[i].projectid + ")' style='font-size:22px;margin-left: 32px;'></i><i class='ui-tooltip fa fa-trash-o' onclick='deleteRecord(" + dt.d[i].projectid + ")' style='font-size: 22px;margin-left: 32px;color:red'></i> </tr>");
}
$("#tblid").DataTable();
},
error: function (result) {
alert("Error");
}
});
});
This is my c# Code:
[WebMethod]
public static List<mProjects> BindCategoryDatatable(int catid)
{
clsProjectBL objcategory = new clsProjectBL();
List<mProjects> modelCategory = new List<mProjects>();
DataTable dtCategory = new DataTable();
//dtCategory = objcategory.GetAllCategoryDetails("admin");
dtCategory = objcategory.GetAllProjectDetails("admin", catid);
if (dtCategory.Rows.Count > 0)
{
modelCategory = (from DataRow dr in dtCategory.Rows
select new mProjects()
{
projectid = Convert.ToInt32(dr["projectid"]),
CategoryID = Convert.ToInt32(dr["CategoryID"]),
projectname = dr["projectname"].ToString(),
Name = dr["Name"].ToString(),
technology = dr["technology"].ToString(),
projectliveurl = dr["projectliveurl"].ToString(),
DisplayOrder = Convert.ToInt32(dr["DisplayOrder"]),
status = Convert.ToBoolean(dr["status"]),
StatusImage = dr["StatusImage"].ToString(),
//Deleted = Convert.ToBoolean(dr["Deleted"])
}).ToList();
}
return modelCategory;
}
The value is not pass through webmethod...
Your back-end required a parameter catid so you have to pass catid to AJAX call as #BenG and #palash answer with data attribute.
data: { catid: 1 }
Or you pass it to the url with format
url: "WebForm7.aspx/BindCategoryDatatable?catid=" + YOUR_ID.
Otherwise, it will not be worked because BindCategoryDatatable return an empty list.
I want to return javascript function from asmx as string like following..
All html tags return but checkNewMsg variant 'script tag' doesnt return!
What happens really ?
Please advice
<script type="text/javascript">
function getWindow(FromUserID, UserID, PerID, UserName) {
$.ajax({
type: "POST",
url: "TestMessageService.asmx/OpenWindow",
data: "{'FromUserID': '" + FromUserID + "', 'ClickedUserID': '" + UserID + "', 'ClickedPerID': '" + PerID + "', 'ClickedUserName': '" + UserName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var msgs = response.d;
$('#div_Panel').append(msgs).fadeIn("slow");
var elements = $('.panelContent');
for (var i = 0; i < elements.length; i++) {
elements[i].scrollTop = elements[i].scrollHeight;
}
},
failure: function (msg) {
$('#div_Panel').text(msg);
}
});
}
</script>
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string OpenWindow(string FromUserID, string ClickedUserID, string ClickedPerID, string ClickedUserName)
{
string checkNewMsg = "<script type=\"text/javascript\">window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }</script>";
StringBuilder sb = new StringBuilder();
sb.Append(checkNewMsg + "<div class=\"ch_Box\">");
sb.Append("<div class=\"ch_Header\">");
sb.Append("<div style=\"float:left;margin-top: 9px;margin-left: 8px;\"><img src=\"Images/Status.png\"></div>");
sb.Append("<div id=\"roomUsers\" class=\"ch_HeaderItem\">" + ClickedUserName + "</div>");
sb.Append("<div onclick=\"closePanel(this)\" style=\"width: 23px; height: 27px; cursor: pointer; position: absolute; margin-left: 232px;\"><img style=\"height: 20px; margin-top: 4px;\" src=\"Images/close.png\"></div>");
sb.Append("<div id=\"cont_" + ClickedUserID + "\" class=\"panelContent\">" + FillMessages(roomID, FromUserID.ToInt()) + "</div>");
sb.Append("<div class=\"ch_Text\">");
sb.Append("<input id=\"msg_" + FromUserID + "_" + ClickedUserID + "_" + ClickedPerID + "_" + roomID + "\" type=\"text\" class=\"inp\" onkeypress=\"PushText(this)\" autocomplete=\"off\" /></div>");
sb.Append("</div></div>");
return sb.ToString();
}
I don't know why doesn't return script tag an asmx but when i remove the tag and then in the js side while i add script' tag before return value the problem is solved.
Just like this;
In asmx side;
string checkNewMsg = "window.setInterval(fc_" + ClickedUserName.Replace(" ", "") + ", 10000); function fc_" + ClickedUserName.Replace(" ", "") + "() { alert('" + ClickedUserName + "'); }#func#";
In Js Side;
success: function (response) {
var msgs = response.d;
var arrCont = msgs.split('#func#');
var MsgCont = "<script type=\"text/javascript\">" + arrCont[0] + "<\/script>";