send fieldset values by jquery - c#

look at this code :
[WebMethod]
public static string GetFacilities(string id)
{
int hotelid = System.Convert.ToInt32(Tools.DecryptString(id));
string ret = "";
foreach (var item in new FacilityGroupBL().Load())
{
if(item.Facilities.Count != 0)
{
ret += "<fieldset>";
if (item.Facilities.Count() != 0)
{
foreach (var subitem in item.Facilities)
{
if (subitem.HotelFacilities.Where(obj => obj.HotelId == hotelid).Count() != 0)
ret += "<input type='checkbox' checked='false' />" + subitem.Name;
else
ret += "<input type='checkbox' checked='true' />" + subitem.Name;
}
}
else
{
ret += "There is no facility in this fieldset.";
ret += "</fieldset>";
}
}
}
return ret;
}
by this code i load some checkboxes in a DIV,then user change some checkboxes and press the SAVE button.at this time ,i should send the values of these checkboxes to server to update my data in database.by i dont know how?:( please help
note: my default code for this probem is here but it does not work($("#FacilitiesDIV input[type=checkbox]").serializeArray() is empty)
$.ajax({
type: "POST",
url: "HotelsList.aspx/SaveFacilities",
data: "{ 'id' : '" + $("#HiddenField").val() + "', 'Facilities' : '" + $("#FacilitiesDIV input[type=checkbox]").serializeArray() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function () {
$('#dialogMessage').dialog('open');
$('#dialogMessage span').html("Operation Error");
}
});

$("#FacilitiesDIV input[type=checkbox]").serializeArray() since you are referring element using "#" then you need to give the fieldset element an Unique ID assuming you have
html like
<fieldset> <input type='checkbox' checked='false' /> some text
<input type='checkbox' checked='false' /> some text
</fieldset>
set the id to element <fieldset id = 'FacilitiesDIV'>

I believe it should work if you give each checkbox a name, ie:
<input type='checkbox' checked='false' name="mycheckboxes" />

Related

Model binding returns NULL

Im trying serialize form and binding into model, but some how child of model InsertToUsertbls returns NULL. Can any help me please :)
I have the following model:
public class MangeAddUsers
{
public List<InsertToUsertbl> InsertToUsertbls { get; set; }
public class InsertToUsertbl
{
public InsertToUsertbl()
{
}
public int PX2ID { get; set; }
public string CustomerNR { get; set; }
public string SellerPersonCode { get; set; }
public string NameOfCompany { get; set; }
public string CompanyNo { get; set; }
}
}
JavaScript to Get data and than load them into form:
<script>
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function myfunction() {
$.ajax({
type: "GET",
url: "/Account/GetCustomerContactInfo",
data: {ids: '10883'},
dataType: 'json',
traditional: true,
success: function (values) {
var holderHTML = "";
for (var i = 0; i < values.length; i++) {
value = values[i]
if (value != null) {
var guid = uuidv4();
holderHTML += '<tr id="row' + value.CustomerNo + '">';
holderHTML += '<input type="hidden" name="InsertToUsertbls.Index" value="' + guid + '" />';
holderHTML += '<td><input class="inpt-tbl" type="hidden" id="CustomerNR" name="InsertToUsertbls[' + guid + '].CustomerNR" value="' + value.CustomerNo + '" /></td>';
holderHTML += '<td><input class="inpt-tbl" type="hidden" id="NameOfCompany" name="InsertToUsertbls[' + guid + '].NameOfCompany" value="' + value.NameOfCompany + '" /></td>';
holderHTML += '<td><input type="hidden" id="CompanyNo" name="InsertToUsertbls[' + guid + '].CompanyNo" value="' + value.CompanyNo + '" /></td>';
holderHTML += '<input type="hidden" id="SellerPersonCode" name="InsertToUsertbls[' + guid + '].SellerPersonCode" value="' + value.SalgePersonCode + '" />';
holderHTML += '</tr>';
}
}
$('#output').append(holderHTML);
},
error: function () {
console.log('something went wrong - debug it!');
}
})
};
</script>
And when data load into form:
<form id="mangeUserFrom">
<div id="output">
<tr id="row10883">
<input type="hidden" name="InsertToUsertbls.Index" value="fd3424ab-160d-4378-af65-ad2b790812ec">
<td>
<input class="inpt-tbl" type="hidden" id="CustomerNR" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CustomerNR" value="10883">
</td>
<td>
<input class="inpt-tbl" type="hidden" id="NameOfCompany" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].NameOfCompany" value="Some Name">
</td>
<td>
<input type="hidden" id="CompanyNo" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CompanyNo" value="849">
</td>
<input type="hidden" id="SellerPersonCode" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].SellerPersonCode" value="TT">
</tr>
</div>
</form>
<button type="button" id="createuser" onclick="PostForm();">POST</button>
JavaScript for serializing:
<script>
function PostForm() {
var formdata = $("#mangeUserFrom").serializeArray();
console.log(formdata);
$.ajax({
"url": '#Url.Action("MangeCreateUsers", "Account")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
This is the result of the serialization:
{name: "InsertToUsertbls.Index", value: "fd3424ab-160d-4378-af65-ad2b790812ec"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CustomerNR", value: "10883"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].NameOfCompany", value: "Some Name"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CompanyNo", value: "849"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].SellerPersonCode", value: "TT"}
This is my controller method I'm trying to POST to:
[HttpPost]
public JsonResult CreateCustomers(CreateCustomers model)
{
return Json(model, JsonRequestBehavior.AllowGet);
}
Screenshots:

jqplot - pass variable via ajax to C# page

I am unable to retrieve values passed by $.ajax on my c# page.
I am using jqplot and I want to pass two pieces of information. One is stored in a hidden field called 'hidden_plateid' and the second piece of information is from a dropdown box called 'SampleNumberList'
This is the hidden field
<input type="text" name="hidden_plateID" id="hidden_plateID" hidden="hidden" runat="server" />
And this is the drop down box:
<select name="SampleNumberList" class="DropDownBox_editjob" id="SampleNumberList">
<option value="--SELECT--"></option>
<option value="001r">001r</option>
<option value="002r">002r</option>
</select>
I simply then say that everytime, someone selects from the dropdown box, to get and get the information from the db and plot the graph
$('#SampleNumberList').on('change', function (e) {
var ajaxDataRenderer = function (url, plot, options) {
var ret = null;
$.ajax({
data: {
PlateID2: options.PlateID,
SampleID2: options.SampleID,
},
async: false,
url: url,
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
return ret
};
var jsonurl = "SpectraData.aspx";
var plot2 = $.jqplot('chartdiv', jsonurl, {
title: "AMIRA",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl, PlateID: $('#hidden_plateID').val(), SampleID: $('#SampleNumberList').val()
}
});
});
I use Request.Querystring to try and retrieve the value in the c# file but so far, I get nothing
if (Request.QueryString["PlateID2"] != null)
{
PlateID = Request.QueryString["PlateID2"].ToString();
}
if (Request.QueryString["SampleID2"] != null)
{
SampleID = Request.QueryString["SampleID2"].ToString();
}
You are trying to retrieve values from a query string , yet you are passing the parameters as json.
In order to retrieve them as a query string params, you need to pass them along your url.
$.ajax({
async: false,
url: url + "?PlateID2=" + options.PlateID + "&SampleID2=" + options.SampleID + "",
dataType: "json",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In reality, the right way to do this is to pass params as a json string and intercept in the code behind.
$.ajax({
url: url/Somemethod,
type: 'POST',
dataType: 'json',
data: "{'PlateID2':'" + options.PlateID + "','SampleID2':'" + options.SampleID + "'}",
success: function (data) {
alert(data);
ret = data;
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
In your codebehind :
[WebMethod]
public static void Somemethod(string PlateID2,string SampleID2)
{
}

Check Items Already exista in the Table using Jquery

I have a Select2 list and added multiple items to the table.But i wanted to check if items already exists in the table or not first and IF not only then add new item But below my code doesn't work.
In this code everytime it shows Not Found & add duplicate rows
HTML Part
<select id="select-product" multiple style="width: 300px">
</select>
Code
$("#select-product").change(function () {
debugger;
var $option = $('#select-product option');
if ($("#select-product option[value='ProductCode']").length > 0) {
alert("Found");
}
else
{
alert("Not Found");
}
$option.each(function () {
if ($(this).is(':selected')) {
debugger;
var itm = $(this).is(':selected');
var temp = $(this).attr('ProductCode');
var row = '<tr>';
row += '<td class="itmcode">' + $(this).attr('ProductCode') + '</td>';
row += '<td class="itmname">' + $(this).text().replace(temp, " ") + '</td>';
row += '<td class="unit">' + $(this).attr('Unit_UnitId') + '</td>';
row += '<td class="retprice" dir="rtl" align="right">' + $(this).attr('RetailPrice') + '</td>';
row += '<td class="col-md-1 inpqty" dir="rtl">' + '<input type="text" class="input-qty form-control col-md-3 center-block input-sm" data-id="' + $(this).val() + '" data-prod-id="' + $(this).attr('Value') + '">' + '</td>';
row += '<td class="col-md-1 disc" dir="rtl">' + '<input type="text" class="input-disc form-control input-sm">' + '</td>';
row += '<td class="tot" dir="rtl" align="right">0</td>';
row += '<td class="imgdel"><img class="btn-img-del" src="../Images/delete.png" alt="" title="Delete" /></td>';
row += '</tr>';
table.append(row);
}
});
$('#select-product').select2('data', null);
});
Multiple Products Code
function CallMultipleProducts() {
$.ajax({
type: "POST",
url: '/Sales/GetMultipleProducts',
contentType: "application/; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
debugger;
if (msg._productlist.length > 0) {
debugger;
$.each(msg._productlist, function (index, item) {
debugger;
$('#select-product').append($("<option></option>")
.attr("Value", item.ProductId)
.attr("RetailPrice", item.RetailPrice)
.attr("ProductCode", item.ProductCode)
.text((item.ProductCode) + " " + (item.ProductName))
);
});
}
}
// error: AjaxError
})
}
Make sure that you have only select item with unique id="select-product" throughout your html.
Try below code, use .find()
if ($("#select-product").find("option[value='ProductCode']").length > 0) {
alert("Found");
}
Please try adding the below option to your select2 options if the element is input type="text",
$("#select-product").select2({
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
If you are using <select> element, I'm afraid you can't use this option. You have to use input instead. You might find something useful here.

How to add Items in jcarousel ? in C#

I would like to add Items in jcarousel using c# Webmethod + jquery Ajax
for that i made something like this :
my Html is like :
<div>
<ul id="mycarousel" class="jcarousel-skin-tango" style="float: left">
</ul>
</div>
Jquery code for jcarousel and Ajax Method is like this :
$("#mycarousel").empty();
var element =jQuery('#mycarousel');
$.ajax({
url: "Home.aspx/GetProjectData",
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: "{}",
async: false,
success: function (response) {
if (response.d != null) {
//$.each(response.d, function (i, response) {
$("#mycarousel").html('response.d');
element.jcarousel(
{
pager: true,
visible: 6
});
}
else {
}
},
error: function (xhr) {
}
});
and webmethod is like this :
[WebMethod]
public static List<string> GetProjectData()
{
// here i have 3 list in returnvalue
foreach (var item in returnvalue)
{
var classvalue = item.Soid + "|"
+ item.ProjectTitle + "|"
+ item.Role + "|"
+ item.StartDate + "|"
+ item.EndDate + "|"
+ item.Location.Country + "|"
+ item.Location.State + "|"
+ item.Location.City + "|";
string Template = "<li><img src='../Images/DefaultPhotoMale.png' class='"+ classvalue + "' width='40' height='40' alt='image'/></li>";
list.Add(Template);
}
return list;
}
but problem is , i am not able to images in jcarousel , i only see white box, i am not able to seee images inside, why ?
I'm not sure but wouldn't you need to append the elements sort of like this:
var listItem = $(response.d); //I'm guessing reponse.d is your returned li
element.append(listItem);

ReferenceError: getMessage not defined

I am building a messaging area similar to facebook and I am using ajax with jquery and a asmx web service to serve the html to the client. My li click event works when the content is first loaded on page load using c#, but when ajax runs and refreshes the content from the web service the li event doesn't work anymore.
This an example of the html that is returned from the web service
<ol class="messagesrow" id="messages">
<li id="2345">
<div>Test Element</div>
</li>
</ol>
Web service markup
[WebMethod]
public string GetMessagesByObject(string id, string objectid, string userid, string timezone)
{
string output = string.Empty;
try
{
StringBuilder str = new StringBuilder();
DataSet results = results from store procedure
str.Append("<ol class=\"messagesrow\" id=\"messages\">");
for (int i = 0; i < results.Tables[0].Rows.Count; i++)
{
DataRow row = results.Tables[0].Rows[i];
DateTime date = Convert.ToDateTime(row["CreateDate"].ToString()).AddHours(Convert.ToDouble(timezone));
if (!TDG.Common.CheckStringForEmpty(row["ParentMessageID"].ToString()))
{
str.Append("<li id=\"" + row["ParentMessageID"].ToString() + "\">");
}
else
{
str.Append("<li id=\"" + row["MessageID"].ToString() + "\">");
}
str.Append("<div style=\"width:100%; cursor:pointer;\">");
str.Append("<div style=\"float:left; width:25%;\">");
if (!TDG.Common.CheckStringForEmpty(row["ImageID"].ToString()))
{
str.Append("<img src=\"/Resources/getThumbnailImage.ashx?w=48&h=48&id=" + row["ImageID"].ToString() + "\" alt=\"View Profile\" />");
}
else
{
str.Append("<img src=\"/images/noProfileImage.gif\" alt=\"View Profile\" />");
}
str.Append("</div>");
str.Append("<div style=\"float:left; width:75%; padding-top:4px;\">");
str.Append("<strong>" + row["WholeName"].ToString() + "</strong>");
str.Append("<br />");
if (row["BodyMessage"].ToString().Length < 35)
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString() + "</span>");
}
else
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString().Substring(0, 35) + "</span>");
}
str.Append("<br /><span class=\"smallGreyText\">" + String.Format("{0:g}", date) + "</span>");
str.Append("</div>");
str.Append("</div>");
str.Append("</li>");
}
str.Append("</ol>");
output = str.ToString();
}
catch (Exception ex)
{
throw ex;
}
return output;
}
Jquery markup
$(document).ready(function () {
$("ol#messages li").click(function () {
var id = $(this).attr("id");
getMessage(id);
});
});
function getMessage(id) {
var timezone = $('#<%= hdfTimezone.ClientID %>').val()
var userid = $('#<%= hdfUserID.ClientID %>').val()
$.ajax({
type: "POST",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Resources/MessageWebService.asmx/GetMessage",
data: "{'id':'" + id + "','timezone':'" + timezone + "','userid':'" + userid + "' }",
success: function (data) {
$('#<%= hdfMessageID.ClientID %>').val(id);
$('#<%= ltlMessages.ClientID %>').html(data.d);
},
error: function (data) {
showError(data.responseText);
}
});
}
Since your list items are dynamic, you should delegate the event from the ol.
$(document).ready(function () {
$("#messages").delegate("li","click",function () {
getMessage(this.id);
});
});
The error you are getting ReferenceError: getMessage not defined shouldn't happen with the given code.

Categories