I have an web api to post data in the table when data entered in html page through jquery.
The web api function is as:
public HttpResponseMessage Post(User user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
And the html page with jquery script is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<h2>All users</h2>
<ul id="users" />
</div>
<div>
<h2>Insert New User</h2>
First Name : <input type="text" id="firstName" /><br />
Last Name : <input type="text" id="lastName" /><br />
City : <input type="text" id="city" /><br />
Email : <input type="email" id="email" /><br />
Password : <input type="password" id="password" /><br />
Phone number: <input type="number" id="phone" /><br />
<input type="button" id="btnsave" value="Save" onclick="Post();" />
<p id="P1" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/user';
$(document).ready(function () {
// Send an AJAX request
getuserlist();
});
function getuserlist() {
$.getJSON(uri)
.done(function (data) {
$('#users').html('');
// On success, 'data' contains a list of users.
$.each(data, function (key, item) {
// Add a list item for the user.
$('<li>', { text: formatItem(item) }).appendTo($('#users'));
});
});
}
function formatItem(item) {
return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
}
function Post() {
jQuery.support.cors = true;
var source = {
'firstName': $('#firstName').val(),
'lastName': $('#lastName').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'city': $('#city').val(),
'password': $('#password').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/user",
data: source,
success: function (data) {
var strResult = "<table><th>Returned Message</th>";
// $.each(data, function (index, data) {
strResult += "<tr><td> " + source.email + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
},
error: function (x, y, z) {
var strResult = "<table><th>Error Message</th>";
// $.each(data, function (index, data) {
strResult += "<tr><td> " + x.responseText + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
// alert(x + '\n' + y + '\n' + z);
}
//success: function (data) {
// //alert(data);
// getuserlist();
// // alert(jQuery.parseJSON(data));
//},
//error: function (error) {
// jsonValue = jQuery.parseJSON(error.responseText);
// //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
//}
});
});
</script>
</body>
</html>
when I click on the button to add anew user,the post() function is not working.
the page remains the same,no action,no error.
please help!
Thanks!
Firstly the url that you are posting to should be "/api/user/Post".
Output
There are several other JavaScript errors in the posted code that I had to fix. As other's have mentioned in the comments these errors were shown in the console. Knowing how to debug using the developer tools is invaluable and worth investing time to learn them.
Here is the updated code fixed:
<div>
<h2>All users</h2>
<ul id="users" />
</div>
<div>
<h2>Insert New User</h2>
First Name : <input type="text" id="firstName" /><br />
Last Name : <input type="text" id="lastName" /><br />
City : <input type="text" id="city" /><br />
Email : <input type="email" id="email" /><br />
Password : <input type="password" id="password" /><br />
Phone number: <input type="number" id="phone" /><br />
<input type="button" id="btnsave" value="Save" onclick="Post();" />
<p id="P1" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/user';
$(document).ready(function () {
// Send an AJAX request
getuserlist();
});
function getuserlist() {
$.getJSON(uri)
.done(function (data) {
$('#users').html('');
// On success, 'data' contains a list of users.
$.each(data, function (key, item) {
// Add a list item for the user.
$('<li>', { text: formatItem(item) }).appendTo($('#users'));
});
});
}
function formatItem(item) {
return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
}
function Post() {
jQuery.support.cors = true;
var source = {
'firstName': $('#firstName').val(),
'lastName': $('#lastName').val(),
'email': $('#email').val(),
'phone': $('#phone').val(),
'city': $('#city').val(),
'password': $('#password').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/user/Post",
data: source,
success: function (data) {
var strResult = "<table><th>Returned Message</th>";
$.each(data, function (index, data) {
strResult += "<tr><td> " + source.email + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
});
},
error: function (x, y, z) {
var strResult = "<table><th>Error Message</th>";
$.each(x, function (index, data) {
strResult += "<tr><td> " + x.responseText + " </td></tr>"
strResult += "</table>";
$("#divResult").html(strResult);
// alert(x + '\n' + y + '\n' + z);
});
}
//success: function (data) {
// //alert(data);
// getuserlist();
// // alert(jQuery.parseJSON(data));
//},
//error: function (error) {
// jsonValue = jQuery.parseJSON(error.responseText);
// //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
//}
});
};
</script>
I have also made the assumption that your User object is as follows:
public class User
{
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string city { get; set; }
public string password { get; set; }
}
Related
I am trying to create a search filter, each time I insert data type an int, it throws an error to below line and need some help, as to how to resolve it.
When I step into the method Json GetStringData where error is thrown, I saw the 'SearchValue' is undefined.
How does this become possible? How can I change this in order for this code to work? As in where the error is thrown, the data does come back from record, the issue is when search filter is inserted.
ASP.Net
//GET: SearchPeople-ID.
public ActionResult SearchPeopleDetails()
{
RegCoursesViewModel regCoursesView = new RegCoursesViewModel();
return View(cb.RegPeopleLists.ToList());
}
// GET://Passing-Data-Back as Json.
public JsonResult GetSearchingData(string SearchBy, string SearchValue)
{
List<eNtsaRegPeopleLists> regPeopleLists = new List<eNtsaRegPeopleLists>();
if(SearchBy == "ID")
{
try
{
int Id = Convert.ToInt32(SearchValue); // Incorrect string format
regPeopleLists = cb.RegPeopleLists.Where(v => v.LoginID == Id || SearchValue == null).ToList();
}catch(FormatException)
{
Console.WriteLine("{0} Is Not A ID ", SearchValue);
}return Json(regPeopleLists, JsonRequestBehavior.AllowGet);
}
else
{
regPeopleLists = cb.RegPeopleLists.Where(v => v.Name.StartsWith(SearchValue) || SearchValue == null).ToList();
return Json(regPeopleLists, JsonRequestBehavior.AllowGet);
}
}
public class eNtsaRegPeopleLists
{
public string Name { get; set; }
[Key]
public int LoginID { get; set; }
public string SISID { get; set; }
public string Role { get; set; }
public DateTime LastActivity { get; set; }
public decimal TotalActivity { get; set; }
}
Javascript
<!--Javascript functionality for filter search-->
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#SearchLv").keyup(function () {
var SearchBy = $("#SearchBy").val();
var SearchValue = $("#Search").val();
var SetData = $("#DataSearching");
SetData.html("");
debugger;
$.ajax({
type: "post",
url: "/Home/GetSearchingData?SearchBy=" + SearchBy + "&SearchValue=" + SearchValue,
contentType: "html",
success: function (result) {
if (result.length == 0) {
SetData.append('<tr style="color:red"><td colspan="3">No Match Data</td></tr>')
}
else {
$.each(result, function (index, value) {
var Data = "<tr>" +
"<td>" + value.LoginID + "</td>" +
"<td>" + value.Name + "</td>" +
"<td>" + value.Role + "</td>" +
"<td>" + value.SIS_ID + "</td>" +
"<td>" + value.LastActivity + "</td"> +
"<td>" + value.TotalActivity + "</td>"
"</tr>";
SetData.append(Data);
});
}
}
});
});
});
</script>
View
#model IEnumerable<eNtsaRegistrationTraining.Models.eNtsaRegPeopleLists>
<br />
<br />
<div class="form-group row float-right">
<form class="form-group ml-lg-auto">
<div class="input-group input-group-sm">
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="SearchLv">
<div class="input-group-append">
<button class="btn btn-navbar" type="submit">
<i class="fas fa-search"></i>
</button>
</div>
</div>
</form>
</div>
<!--Select-ID-->
<select id="SearchBy">
<option value="ID">LoginID</option>
<option value="Name">Name</option>
<option value="Roles">Roles</option>
</select>
<br />
<br />
<table class="table table-bordered">
<thead>
<tr>
<th>LoginID</th>
<th>Name</th>
<th>Roles</th>
<th>SISID</th>
<th>LastActivity</th>
<th>TotalActivity</th>
</tr>
</thead>
<!--Tbody here-->
<tbody id="DataSearching">
#foreach(var Item in Model)
{
<tr>
<td>#Item.LoginID</td>
<td>#Item.Name</td>
<td>#Item.Role</td>
<td>#Item.SISID</td>
<td>#Item.LastActivity</td>
<td>#Item.TotalActivity</td>
</tr>
}
</tbody>
</table>
search input id is {SearchLv} in your view.
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="SearchLv">
Either change the id in view
<input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search" id="Search">
Or you can change on javascript
var SearchValue = $("#SearchLv").val();
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:
I'm trying to call $.ajax method to retrieve NORTHWND Employees details based on the search criteria. But, for some reason, country, and title variable are always returning null. I am not understanding where I am doing wrong.
Below is the clear explanation.
Below is the code in AjaxDemoRequestPage.aspx
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country = $("#txtCountry").val();
data.title = $("#txtTitle").val();
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
Below is the code in PostTarget.aspx.cs page. In this page, when debugging I am always getting country, and title as null.
public partial class PostTarget : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var country = Request.Form["country"];
var title = Request.Form["title"];
var db = new NORTHWNDEntities();
var emps = db.Employees
.Where(x => x.Country.Contains(country) || x.Title.Contains(title))
.Select(x => new EmployeeSearchResult
{
EmployeeID = x.EmployeeID,
FirstName = x.FirstName,
LastName = x.LastName
});
Response.Clear();
Response.Write(JsonConvert.SerializeObject(emps));
Response.Flush();
Response.End();
}
}
Can anyone please suggest me where I am doing wrong?
The contentType should be this:
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
My blunder mistake was that I never made call to $.ajax method. Below is the modified and working code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
$.ajax(data);
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
ID generated by ASP.NET will not same as you have given. this is the reason you are getting null value .
You can access ASP.NET control in javascript in this way.
document.getElementById('<%= txtCountry.ClientID %>').value
And also you can simple use html button instead of ASP.NET button for making ajax request.
Here is your updated code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
My project is MVC 5 c# I am using jquery.fileupload would like to know how I can pass additional values to the controller, in this case is the file description.
View:
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<input id="description" name="description" value="description" />
Script:
$(document).ready(function () {
var description = $("#description").val();
$('#fileupload').fileupload({
dataType: 'json',
url: '/Home/UploadFiles',
autoUpload: true,
done: function (e, data) {
$('.file_name').html(data.result.name);
$('.file_type').html(data.result.type);
$('.file_size').html(data.result.size);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});
Controller:
public ContentResult UploadFiles()
{
var r = new List<UploadFilesResult>();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileName = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
r.Add(new UploadFilesResult()
{
Name = hpf.FileName,
Length = hpf.ContentLength,
Type = hpf.ContentType
});
}
return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
}
You can send additional data to server using formData property.
See below:
$('#fileupload').fileupload({
formData: {
param1: 'test2',
param2: "test3",
param3: "test3"
}
});
The formData option can be used to set additional form data programmatically.
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" />