Setting form values when jQuery datatable row is clicked - c#

I have a web form with a jQuery datatable in it. When a particular row is clicked I get the row data and need to set the values of the controls on the page.
I can get the row values, I set breakpoints and can see the row values fetched are correct but for some reason the control values don't get set (for example, a label's text). This is what I have (watered down version):
$(document).ready(function () {
var zTable = $("#fcTable").DataTable({
"bServerSide": true,
"bDestroy": true,
"sAjaxSource": "../fc.asmx/GetItems",
"bJQueryUI": true,
"fnServerParams": function (aoData) {
aoData.push({ "name": "FacilityID", "value": $('#<%= ddlFacility.ClientID %> option:selected').val() });
},
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success":
function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#fcTable").show();
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
alert(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
}
});
$('#fcTable tbody').on('click', 'tr', function () {
var currentRowData = zTable.row(this).data();
processRow(currentRowData);
});
})
function processRow(row) {
debugger
$("#<%= rblResp.ClientID %> input[type=radio]").prop('checked', false);
$("#<%= cblResp.ClientID %> input[type=checkbox]").prop('checked', false);
var sQuestion = row[2];
// None of these sets the label's text
$('#<%= lblQuestion.ClientID %>').val(sQuestion);
$('#<%= lblQuestion.ClientID %>').innerHTML = sQuestion;
}
Update
I can get it to work using
$('#<%= lblQuestion.ClientID %>')[0].innerHTML = sQuestion;
i.e. adding an array index [0].
But is this the correct way of doing it?

The issue is that $('#<%= lblQuestion.ClientID %>') returns a jQuery object, and innerHTML is standard JavaScript, and won't work as wanted on a jQuery object.
The [0] on the end of the object gives you the DOM node (first property of the object), which is what innerHTML needs.
The correct way to do it in pure jQuery would be just:
$('#<%= lblQuestion.ClientID %>').html(sQuestion);
FYI, you can set ClientIDMode="Static" on the input, to avoid asp.Net overriding the ID you give it in your HTML, and so avoid all the <%=... stuff in your JavaScript, which works much better if you get to the point where you want to split the JavaScript out into its own file.

Related

set buffer false during jQuery ajaxSubmit

I want to run ASPX page in ASP page.
So I use ajaxSubmit and print to "target div" get from ASPX page like this:
var data = new FormData();
data.append("email", $("#EMAIL").val());
data.append("pass", $("#PASS").val());
data.append("store", $("#STORE").val());
if ($("#STORE").val()!="" && $("#EMAIL").val()!="" && $("#PASS").val()!="") {
e.preventDefault();
$(this).ajaxSubmit({
data: $(this).serialize(),
target: "#formres",
async: true,
global: false,
cache: false,
beforeSubmit: function () {
},
success: function () {
if($("#yu").val()!="yes")
{
setTimeout(function(){
window.location.href = $("#yu").val();
},2000);
}
},
resetForm: false
});
But anything display before process ends.
I think it must be something like "Response.Buffer=false" or "flush()" at jquery too.(I use "cache: false," for this purpose)
I set Reponse.Buffer =false at asp and aspx page.
But it still not working. Could anyone help me?

Use jQuery Select2 with ASP.NET MVC

I'm trying to use Select2 in Razor in ASP.NET MVC. But I can't get work.
$(document).ready(function () {
$(".genreOptions").select2({
tags: true,
ajax: {
url: 'http://localhost:65148/NewProfile/Genres',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
id: item.Id, //id part present in data
text: item.Genre //string to be displayed
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1
});
#Html.DropDownListFor(x => x.BandProfile.Genres, Enumerable.Empty<SelectListItem>(), new { #class="genreOptions", multiple = "multiple", style ="width: 100%;"} )
The searching for tags works fine. But when I post the form, the count of the input field Is 0. How can I capture the data from the input form?
#Bryan I build up a javascript array and pass it with ajax to the server. Seems to work ok for my purposes. Perhaps you could try that. The selectors I put below will be different than what you need but here is the general idea...
On Click
$('#submitButton').click(function () {
fillHiddenInput();
var dataToSend = $('#hiddenInput').val();
//Submit the form with ajax or however you want to get dataToSend to server
});
FillHiddenInput function...
var fillHiddenInput = function () {
$('#hiddenInput').val("");
var stuff = [];
$('.ms-selection .ms-list li ul').children('li').each(function (){
if ($(this).hasClass('ms-selected'))
{
stuff.push($(this).children('span').text());
}
});
$('#hiddenInput').val(stuff);
}

fullcalendar: call web service function when next or prev button is pressed

I want to load events of only one month at a time. At first, show the event of one month in one page and when next or prev button is pressed, show the event of that month from database via web service (C#). How can I achieve that?
I also want to get data from one month only and I want to send the selected year, month value to the web service so it can send the data of only specific month.
My current jquery code is:
jQuery(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json",
url: "FullcalenderwithWebservice.asmx/GetEvents",
dataType: "json",
success: function (data) {
$("div[id=loading]").hide();
$("div[id=fullcal]").show();
$('div[id*=fullcal]').fullCalendar({
header: {
left: '',
center: 'title',
right: 'today prev,next'
},
editable: false,
events: $.map(data.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
event.className = item.className.toString()
return event;
})
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
});
also
$('.fc-button-prev span').click(function(){
alert('prev is clicked, do something');
});
is not working.
You might want to use viewdisplay e.g.
viewDisplay: function(view) { var next = view.title; alert(next); }
Here I am using that event to go and get the next batch of data from a webservice and render it.
$(document).ready(function () {
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
},
eventSources: [ getCalData() ],
header: {
left: 'prev,next today',
center: 'title',
right: ''
},
viewDisplay: function (view) {
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('addEventSource', getCalData());
$('#calendar').fullCalendar('rerenderEvents');
}
});
});
function getCalData() {
var source = [{}];
$.ajax({
async: false,
url: '/mysite/GetWeekData',
data: { myParam: $('#calendar').fullCalendar('getView').visStart },
success: function (data) {
$(data).each(function () {
source.push({
title: $(this).attr('title'),
start: $(this).attr('start'),
});
});
},
error: function () {
alert('could not get the data');
},
});
return source;
}

JSON TinyMCE return value "\t"

Should I use another variable for "streszczenie"? or what should I do?
In my opinion in TinyMCE body have html but I get only "\t" Pobably I have got problem with JS
this is new problem - this question is related with this link. I added this for other users
this I write in TinyMCE
this I get from TinyMCE textarea "streszczenie"
As you can see there is text ghhfgh but I can`t get this text
Now I have got problem with execute JSON
<script type="text/javascript">
function Save() {
tinyMCE.triggerSave();
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function() {
},
success: function(data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
I get this but all the time JSON is not execute
When I click button tinyMCE.get('Streszczenie').getContent() is empty I check this and I don`t know why because I have got text into textarea
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var $d = tinyMCE.get('Streszczenie').getContent();
if ($d.length != 0) {
if ($d.val().length != 0) {
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
}
else {
var Streszczenie_controll = 'ewewe';
}
}
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
You are getting the content in wrong way, not by jQuery's val().
To get the tinymce content, just use tinyMCE object reference:
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
// Get the raw contents of the currently active editor
tinyMCE.activeEditor.getContent({format : 'raw'});
// Get content of a specific editor:
tinyMCE.get('content id').getContent()
As mentioned:
http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.getContent
Hope it heled. Polish man : )

Client-side validation against an object in ASP.Net-MVC3?

I have ah HTML5 form with an action defined as follows:
#using (Html.BeginForm("SearchAction", "ResultsController"))
The form takes in two text fields:
<input type="text" name="txtSearchTerm" id="txtSearchTerm" class="frontPageInput" placeholder="Begin your search..." required />
<input type="text" name="txtGeoLocation" id="txtGeoLocation" class="frontPageInput" required />
The txtGeoLocation field is an autocomplete field that is fed from a cached object, fed through the controller and by a model repository class through the following jQuery code:
<script type="text/javascript" language="javascript">
$(function () {
$("#txtGeoLocation").autocomplete(txtGeoLocation, {
source: function (request, response) {
$.ajax({
url: "/home/FindLocations", type: "POST",
dataType: "json",
selectFirst: true,
autoFill: true,
mustMatch: true,
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
document.getElementById("hidLocation").value = ui.item.id;
}
});
});
There's an alert there for debugging. When clicking on the text that drops down, this alert fires, however it does not fire if you type in the whole word and hit submit.
I would like to first, validate the text in the geo text box on the client side, to ensure that it is a value contained in the collection, of not, have the text box in red, communicate that.
Thanks.
You can use jquery remote validation using the [Remote()] attribute to validate the value is in the list. You will have to do the same check on the server side when you post back as well.

Categories