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);
}
Related
Fiddled with every imaginable combination of webapi controller and jquery ajax script which, when debugging, does make a get call to the controller, but it won't parse the data (in debug, the data is there!). PostMan and typing URL into browser works perfectly, so I believe there is (yet another) trick to get jquery.ajax to work.
the WebAPI controller method (which works):
namespace SearchWebsite.Controllers
{
public class MoreInfoController : ApiController
{
private string DBConnStr;
public MoreInfoController()
{
DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem_Data.DBConnStr = DBConnStr;
}
[Route("api/getmoreinfo/{lid}")]
[HttpGet]
public async Task<IHttpActionResult> GetMoreInfo(string lid)
{
var retval = new AppCore.MoreInfo();
if (lid.Length == 36)
{
if (IsGUID(lid))
{
retval = await LiveItem_Data.GetMoreInfoAsync(lid);
}
}
return Ok(retval);
}
}
}
And I get the expected results when I call it via postman or the browser, like so:
https://localhost:44371/api/getmoreinfo/2A116FF3-E6C8-4EE3-88E5-99001DCCE36A
The jquery ajax method:
$(".popInfo").bind("click", function (e) {
var ListID = $(this).parent().parent().find('[id*=hidlid]').val();
$.ajax({
type: "get",
url: "../../api/GetMoreInfo/" + ListID,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
try {
var mi = jQuery.parseJSON(data);
var img = "";
if (mi.IMGLNK != "") { img = "<img src='" + mi.IMGLNK + "' class='img-responsive' />"; }
var title = "<a href='redir?lid=" + ListID + "' target='_blank' >" + mi.NAME + "</a>";
var btnV = "<a href='redir?lid=" + ListID + "' target='_blank' class='btn btn-success' ><span class='glyphicon glyphicon-shopping-cart'></span> Visit Website</a>";
var btnR = '</span> Report Problem';
var details = "<p><p>SKU: " + mi.SKU + "</p><p>MPN: " + mi.MPN + "</p><p>UPC: " + mi.UPC + "</p><p>Ship Weight: " + mi.WT + " lbs</p><p>Last Updated: " + formatJSONDate(mi.MD) + "</p></p>"
$('#moreinfo').find('.modal-title').html(title);
$('#moreinfo').find('.modal-body').html(img + '<p class="descr">' + mi.DESC + '</p>' + details);
$('#moreinfo').find('#btnVisit').html(btnV);
$('#moreinfo').find('#btnReport').html(btnR);
$('#moreinfo').off().modal('show');
} catch (e) {
alert("ERROR:" + e + " data: " + data + " mi: " + mi);
}
},
error: function (err) {
alert("error: " + err);
}
});
});
the try catch and alerts are for troubleshooting, however even though the data is in the data variable while stepping through and debugging, the "data" becomes undefined immediately after using parseJSON(), and, naturally, the variable "mi" is undefined as well and the error I trapped is "SyntaxError: Unexpected token u in JSON at position 0 data: [object Object]".
I'm at a loss as how to remedy this issue. (note: I am in the process of converting old ASMX services into MVC5 WebAPI 2.1 services, so DotNetCore answers won't work as it's a completely different beast, as is MVC4 and below)
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.
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 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>";
I got this error
System.InvalidOperationException: ManageUser Web Service method name
is not valid. at
System.Web.Services.Protocols.HttpServerProtocol.Initialize() at
System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type,
HttpContext context, HttpRequest request, HttpResponse response,
Boolean& abortProcessing)
when I trying to call a webservice method from button click event using ajaxcall
$.ajax() {
type: "POST",
url: "RechargeService.asmx/ManageUser",
//data: "{objUser: " + JSON.stringify(objUsers) + "}",
data: "{Name:'" + Name + "',Address:'" + Address + "',City:'" + City + "',State:'" + State + "',Pincode:'" + Pincode + "',MobileNo:'" + MobileNo + "',Email:'" + Email + "',Password:'" + Password + "',Parameter:'" + Parameter + "',UserRole:'" + UserRole + "',UserStatus:'" + UserStatus + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (data) {
data = JSON.parse(data.d);
if (data.Sucess) {
$("#lblMsg").html('Registration done successfully');
$("#txtEmail").val('');
$("#txtPassword").val('');
$("#txtMobileNo").val('');
$("#txtConfirmPassword").val('');
$('#myModal1').hide();
alert("Your registration completed successfully");
} else {
alert("Already registered with this email id");
$("#txtEmail").val("");
}
},
error: function (xhr, status, error) {
alert(xhr.responseText + " \n " + status + " \n " + error);
alert("There was an error while processing. Please try again after some time.");
}
}
Method
[WebMethod]
Public string ManageUser()
{
}
This code works fine in local after hosting only i get the above error pls help me with this.. Thanks in advance
This can be caused by having null valued parameters in your WebMethod.
For example this:
public string GetDocument(int templateId, int? loginId = null)
...should be changed to this:
public string GetDocument(int templateId, int loginId)
There is a missing brackets () in the ajax function that should be Like this
$.ajax({
//Your Code...
});
Try this...
Possible REASON 1:
did u add this in above the service class
[System.Web.Script.Services.ScriptService]
Possible Reason 2:
Data should have sigle quotes for patameter names as well
data:{'Name':'" + Name + "','Address':'" + Address + "'}