Enum casting in .ajax call - c#

I am trying to delete record from the database using modals, jQuery and javascript but when popup shows I am getting undefined for Gender. How can I represent the value of my enum into a new <td>?
var deleteBtn = null;
function deleteLeague(leagueId, btn) {
deleteBtn = btn;
$.ajax({
type: "POST",
url: "#Url.Action("DeleteLeague", "League")",
data: {
id: leagueId
},
success: function(data) {
$("#leagueTBody").html("");
$("#leagueId").val(leagueId);
$("#leagueTBody").append("<tr><td>" + data.id + "</td>" +
"<td>" + data.leagueType + "</td>" +
" <td> " + data.season.name + "</td>" + " <td> " + data.gender + "</td>" + " <td> " +
data.note + "</td>" +
"</tr >");
},
error: function(req, status, error) {
ajaxErrorHandlingAlert("error", req.status);
}
});
}
Enum:
public enum Gender
{
[Display(Name = "Машки")] Male,
[Display(Name = "Женски")] Female
}
It should be Male or Female in the Gender column.

Related

How can I use autocomplete in a jQuery in an each loop?

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.

Id is not passed to next controller from button in table row created using ajax

I have a form and when i click on search button, i want the data to be displayed in the table without reloading the page. Here i'm using ajax. I managed to display the rows. Supposedly when i click on a select button in the row, the id of the chosen row will be passed to another page. But i got null error because the id value is null. I also put breakpoints to check the id value and it is null. As though the id is not passed at all.
$('#btnPatientSearch').on("click", function (e) {
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: '/consultation/GetPatientLookupList',
type: 'POST',
data: $('#frmPatientLookup').serialize(), // it will serialize the form data
dataType: 'json',
//})
success: function (data) {
$('.firstDL').remove();
$('.subsequentDL').remove();
var rowNo = 0;
for (var i = 0; i < data.length; i++) {
rowNo += 1;
$("#LoadPatientLookupTable tbody").append("<tr Class='odd gradeX subsequentDL'>" +
"<td>" + rowNo + "</td>" +
"<td>" + data[i].paid + "</td>" +
"<td>" + data[i].pidno + "</td>" +
"<td>" + data[i].pidno + "</td>" +
"<td>" + data[i].pname + "</td>" +
"<td>" + data[i].pgender + "</td>" +
"<td style='text-align: center; vertical-align: middle;'><form Class='form-horizontal' role='form' action='#Url.Action("PatientMedicalInfo", "consultation", new { paid = Html.Raw(" + data[i].paid + ") }) method='get'><Button Class='btn btn-default' name='btnSelectPatient' id='btnSelectPatient'>Select</Button></form></td>" +
"</tr>");
//"<td>" + data[i].ToJavaScriptDate(data[i].pdob) + "</td>" +
}
alert('Patient list has been loaded.');
},
error: function () {
alert('Ajax Submit Failed ...');
}
}); // end ajax
}); // end btnPatientSearch
Below is the controller of PatientMedicalInfo:
[HttpGet()]
public ActionResult PatientMedicalInfo(string paid)
{
PatientLookupVM Patient = new PatientLookupVM();
dynamic CurrentPatientDetailsByPtId = Patient.GetCurrentPatientDetailsByPtId(paid);
Patient.LoadCurrentPatientDetails = CurrentPatientDetailsByPtId;
return View(Patient);
}
I also tried passing the id in the same page, but it doesn't work either. Can anyone help me please.. tell me what i'm doing wrong?
#Url.Action() is razor code and is parsed on the server before its sent to the view. Values for data[i].paid do not even exist at the point.
In addition, PatientMedicalInfo() is a GET so there is no need to generate a form tag, and your generating invalid html because of the duplicate id attributes in your <button>
You can simply generate
'<td><button type="button" class="select" data-id="' + data[i].paid + '">Select</button></td>'
and then add the following script to handle the buttons .click() event to redirect
var baseUrl = '#Url.Action("PatientMedicalInfo", "consultation")';
$("#LoadPatientLookupTable tbody").on('click', '.select', function() {
location.href = baseUrl + '?paid=' + $(this).data('id');
});

html table jQuery json value pass

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.

Call javascript function from asmx

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>";

How to save Data In Database to the controller

How to save Data In Database to the controller.i am using jquery to get data from the textbox. please help me.
Contactcontroller.cs
public ActionResult Create(string Name, string Company, string
Regarding, string Email, string Phone, string Message) {
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
try
{
// code
}
catch
{
}
jquery.js
$("#btnSubmit").click(function (event) {
var data = { Name: $("#txtbxName").val(), Company: $("#txtbxCompany").val(), Regarding:
$("#ddlRegarding").val(), Email: $("#txtbxEmail").val(), Phone: $("#txtbxPhone").val(), Message:
$("#txtarMessage").val()
}
$.ajax({
type: "POST",
url: "/Contact/Create", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "html",
success: function (result) {
$("#txtarMessage").val("");
alert(result);
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
alert('Thanks for sending info');
location.reload();
return false;
}
});
});
i am getting data to the textbox using jquery.
now i want to save the whole data in the database through Controller.
Jquery
$.post('/Controller/Create', { Name: $('#Name').val(), Company: "Company", Regarding: "", Email: "",Phone: "",Message: ""}, function (data) {
});
Controller Action
public JsonResult Create(string Name, string Company, string Regarding, string Email, string Phone, string Message)
{
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
return Json(body, JsonRequestBehavior.AllowGet);
}

Categories

Resources