AJAX function is not passing Id parameter to GET method in my controller.
I have this table.
#foreach (var user in Model)
{
<tr>
<td>#user.FirstName</td>
<td>#user.LastName</td>
<td>#user.Email</td>
<td>#string.Join(" , ", user.Roles.ToList())</td>
<td>
<a class="btn btn-primary" onclick="manageRolePopup('#Url.Action("Manage","Role", new {id=user.UserId },Context.Request.Scheme)')">Manage Roles</a>
<partial name="_RoleManagePopup.cshtml" />
</td>
</tr>
}
On click I want to show in popup user first name and last name so I have this in my Controller
[HttpGet]
public async Task<IActionResult> Manage(string userId)
{
var user = await _userManager.FindByIdAsync(userId);
ViewBag.FirstName = user.FirstName;
ViewBag.LastName = user.LastName;
var model = new ManageRoleViewModel();
List<string> roleNames = new List<string>();
foreach(var role in _roleManager.Roles)
{
model.RoleId = role.Id;
roleNames.Add(role.Name);
}
model.UserId = user.Id;
model.RoleNames = roleNames;
return View(model);
}
AJAX
manageRolePopup = (url) => {
$.ajax({
type: "GET",
url: url,
success: function (res) {
$("#form-modal .modal-body").html(res);
$("#form-modal").modal("show");
}
})
}
View
<form method="post" asp-controller="Role" asp-action="Manage" asp-route-UserId="#Model.UserId">
<div class="row">
<div class="col-3">
<h4>#ViewBag.FirstName #ViewBag.LastName</h4>
<div class="form-group">
<select asp-items="#new SelectList(Model.RoleNames)">
<option selected disabled>---Select New Role---</option>
</select>
</div>
</div>
</div>
</form>
When im passing Id like below, everything is good. User is not null, Id parameter also.
<a asp-controller="Role" asp-action="Manage" asp-route-UserId="user.UserId"></a>
Obviously I want to do UPDATE method but for now I just want to have it displayed.
you have to add userId to your ajax url
manageRolePopup = (userId) => {
var url = #Url.Action("Manage","Role");
$.ajax({
type: "GET",
url: url+"?UserId="+userId,
....
Since you have a list of UserIds you need or add UserId data attribute to you ancore tag, or push it as input parameter
<a class="btn btn-primary" onclick="manageRolePopup(#user.UserId)>Manage Roles</a>
but it is better to use modern javascript syntax
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".userBtn", (function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var userId= this.id;
var url = #Url.Action("Manage","Role");
$.ajax({
type: "GET",
url: url+"?UserId="+userId,
....
}));
});
</script>
and view
<a id="#user.UserId" class="userBtn btn btn-primary"> Manage Roles </a>
Related
I have 2 situations here.The first one happens when the page that I route to exists and the other one happens when the page does not exist.Kind of strange.
I try to add an object to my database in asp.net core but when I click the order button on my page it redirects me to the index page of the app(no big deal that can be solved), but my problem is that the object that I send in the POST request is not added to the database.
On the other hand if the page does not exist the object is added to the database(no problem) but I get an Internal Server Error which says "Index" could not be found in the folders that were used in searching for the page.My question is how can I still add the object to my database and still route to a page that I want to route to( for example a thank you for your purchase page).
I will now provide the code for the controller that I used and the endpoints code:
Endpoints:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Controller:
[Route("api/shopping")]
[ApiController]
public class SendItemsController : Controller
{
private AppDbContext _db;
public SendItemsController(AppDbContext db)
{
_db = db;
}
[HttpPost]
[Consumes("application/json")]
public async Task<IActionResult> Save([FromBody] ShoppingCart s)
{
await _db.ShoppingCarts.AddAsync(s);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
public IActionResult Index()
{
return View();
}
}
<form method="post" asp-controller="SendItems" asp-action="Save">
<div class="form-group row">
<div class="col-4">
<label id="clientName"></label>
</div>
<div class="col-6">
<input id="inputName" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientAddress"></label>
</div>
<div class="col-6">
<input id="inputAddress" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label id="clientMail"></label>
</div>
<div class="col-6">
<input id="inputMail" type="text" />
</div>
</div>
<div class="form-group row">
<div class="col-3 offset-4">
<button class="btn btn-primary " id="orderB">ORDER</button>
</div>
</div>
</form>
Here is the javascript that I use on the Cart page:
var orderB = document.getElementById("orderB");
orderB.addEventListener("click", function () {
var inputName = document.getElementById("inputName").value;
var inputAddress = document.getElementById("inputAddress").value;
var inputMail = document.getElementById("inputMail").value;
var auxArray = [];
for (var i = 0; i < productsAux.length; i++) {
if (productsAux[i]!="") {
auxArray[i-1] = { "productName": productsAux[i].titlu, "productPrice": productsAux[i].pret, "quantity": localStorage.getItem(productsAux[i].titlu) };
}
}
var shoppingCart = {
productList: auxArray,
clientName: inputName,
clientAddress: inputAddress,
clientMail: inputMail
};
$.ajax({
type: "POST",
data: JSON.stringify(shoppingCart),
url: "api/Shopping",
contentType: "application/json;charset=utf-8",
})
})
RedirectToPage is used in Razor Page, while this is a MVC project, I think you need to use RedirectToAction.
when I click the order button on my page it redirects me to the index page of the app
So, you want to trigger the Save action in SendItemsController by clicking the order button? What does the request look like, is the url right? Maybe you can show us the client side code.
I made a simple demo and tested with postman, you can have a reference.
[HttpPost]
[Consumes("application/json")]
public async Task<IActionResult> Save([FromBody] ShoppingCart s)
{
await _db.ShoppingCarts.AddAsync(s);
await _db.SaveChangesAsync();
return RedirectToAction("Thanks");
}
[HttpGet("Thanks")]
public IActionResult Thanks()
{
return View();
}
Update:
#section scripts{
<script>
var orderB = document.getElementById("orderB");
orderB.addEventListener("click", function (e) {
e.preventDefault();
var inputName = document.getElementById("inputName").value;
var inputAddress = document.getElementById("inputAddress").value;
var inputMail = document.getElementById("inputMail").value;
var auxArray = [];
for (var i = 0; i < productsAux.length; i++) {
if (productsAux[i] != "") {
auxArray[i - 1] = { "productName": productsAux[i].titlu, "productPrice": productsAux[i].pret, "quantity": localStorage.getItem(productsAux[i].titlu) };
}
}
var shoppingCart = {
productList: auxArray,
clientName: inputName,
clientAddress: inputAddress,
clientMail: inputMail
};
$.ajax({
type: "POST",
url: "/api/Shopping",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(shoppingCart),
})
})
</script>
}
I am new on asp.net mvc and i am trying to redirect home controller after login.ajax is not redirecting to home page.below is my code
My login Page
#using (Html.BeginForm("Authorize", "Login", FormMethod.Post, new { id = "loginform", #class="form-horizontal form-material", onSubmit = "return doLogin(this);", data_restUrl = Url.Action("index", "Home", new { id = 0 }) }))
{
#Html.AntiForgeryToken()
<a href="javascript:void(0)" class="text-center db">
<img src="~/Scripts/plugins/images/eliteadmin-logo-dark.png" alt="Home" />
<br /><img src="~/Scripts/plugins/images/eliteadmin-text-dark.png" alt="Home" />
</a>
<div class="form-group m-t-40">
<div class="col-xs-12">
<input class="form-control" type="text" required="" name="UserKey" id="UserKey" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" name="UserPassword" id="UserPassword" required="" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<div class="checkbox checkbox-primary pull-left p-t-0">
<input id="checkbox-signup" type="checkbox">
<label for="checkbox-signup"> Remember me </label>
</div>
<i class="fa fa-lock m-r-5"></i> Forgot pwd?
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light" type="submit">Log In</button>
</div>
</div>
}
Ajax Call
function doLogin(form) {
$.validator.unobtrusive.parse(form);
loader(true);
if ($(form).valid()) {
var ajaxConfig = {
type: 'POST',
url: form.action,
data: new FormData(form),
success: function (response) {
alert(response);
if (response.success) {
alert();
//$.notify(response.message, "success");
//window.location.href = $(form).attr('data-restUrl');
loader(false);
}
else {
alert("Something went wrong");
//$.notify(response.message, "error");
}
}
}
$.ajax(ajaxConfig);
}
return false;
}
My Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
My Login Controller
[HttpPost]
public JsonResult Authorize(User loginModel) {
try
{
using (POSEntities1 db = new POSEntities1())
{
User usr = db.Users.Where(x => x.UserKey == loginModel.UserKey && x.UserPassword == loginModel.UserPassword).FirstOrDefault<User>();
if (usr != null)
{
Session["UserID"] = usr.UserID;
Session["UserName"] = usr.UserFirstName +" " + usr.UserLastName;
return Json(new { success = true, message = "Login Sucessfully" }, JsonRequestBehavior.AllowGet);
}
else {
return Json(new { success = false, message = "In-valid Username or Password" }, JsonRequestBehavior.AllowGet);
}
}
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
When i click the login button and i am getting below response and ajax call back is not receiving,please guide me whats wrong with my code?
Error link
Could you please do the below changes.
1) On the form
onSubmit = "return doLogin(event);"
2)Add below code to your doLogin(event) method as the first line:
event.preventDefault();
In your Html.BeginForm change the data attribute from data_restUrl to data-restUrl.
Notice here hyphen (-) not an underscore (_).
And in you're ajax success response unhide the below line
window.location.href = $(form).attr('data-restUrl');
if you use newer jQuery >= 1.4.3:
window.location.href = $(form).data("restUrl");//instead of "data-restUrl", we can use "restUrl"
I did some changes on my code which is below there are two changes.
function doLogin(event, form)
{
event.preventDefault();
loader(true);
var ajaxConfig = {
type: 'POST',
url: form.action,
data: new FormData(form),
cache: false,
processData: false,
contentType: false,
success: function (response) {
if (response.success) {
window.location.href = $(form).attr('data-restUrl');
loader(false);
}
else {
alert("Something went wrong");
}
}
}
$.ajax(ajaxConfig);
return false;
}
The data is updated to my database table when the modal form is submitted and closes successfully but what I need is without a page refresh data should be updated in cells of the table.
I am new to JQuery, If someone resolve this matter to me I would really appreciate it.
Here It is the Script which I have placed at the end of my partial view:
function btndbsave(obj) {
var ele = $(obj);
var id = ele.attr("data-model-id");
var itemlist = [];
var name = $("[name = 'NameTxtID']").val();
var phone = $("[name = 'PhoneTxtID']").val();
var email = $("[name ='EmailTxtID']").val();
var AjaxVM = { Id: id, Name: name, Phone: phone, Email: email };
itemlist.push(AjaxVM);
console.log(itemlist)
debugger;
$.ajax({
url: '/Home/Edit', //
dataType: "json",
data: JSON.stringify({ AjaxVM }),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("success");
$('#newmodal').modal('hide');
$('#tbDetails>tbody>td').find("tr").html(AjaxVM);
//$('#tbDetails').find("tbody>tr").append(itemlist);
},
error: function (xhr) {
alert("error");
}
});
};
Partial View As a Modal:
<div class="modal-header">
<h5 class="modal-title">Edit Record</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(x => x.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(x => x.Name, "NameTxt", "NameTxtID", new { htmlAttributes = new { #class = "form-control col-md-6", #name = "Name[]" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(x => x.Phone, "PhoneTxt", "PhoneTxtID", new { htmlAttributes = new { #class = "form-control col-md-6", #name = "Phone[]" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(x => x.Email, "EmailTxt", "EmailTxtID", new { htmlAttributes = new { #class = "form-control col-md-6", #name = "Email[]" } })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-primary btnSave" data-model-id="#Model.Id" onclick="btndbsave(this)" value="Save changes">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
Here it the table of View :
<table id="tbDetails" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Phone</td>
<td>Email</td>
<td>Options</td>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td width="100" class="idField">#item.Id</td>
<td>#item.Name</td>
<td>#item.Phone</td>
<td>#item.Email</td>
<td>
<a class="delete" data-model-id="#item.Id" onclick="Delete(this)"><img src="/UserImages/delete.png" /></a>
<a class="edit-record" data-model-id="#item.Id" onclick="Edit(this)" ><img src="/UserImages/pencil.png" /></a>
</td>
</tr>
}
</tbody>
</table>
Here it is the Controller:
[HttpPost]
public ActionResult Edit(Models.AjaxVM ajaxVM)
{
using (var db = new PracticeEntities())
{
var checkforid = db.AjaxTable.Where(x => x.Id == ajaxVM.Id).FirstOrDefault();
if (checkforid != null)
{
checkforid.Name = ajaxVM.Name;
checkforid.Email = ajaxVM.Email;
checkforid.Phone = ajaxVM.Phone;
db.SaveChanges();
}
else
{
ModelState.AddModelError("error", "Record has not been Updated");
}
return Json(ajaxVM);
}
}
Edit method in a Seperate JS file :
function Edit(obj) {
debugger;
var ele = $(obj);
var url = "/Home/Edit"; // the url to the controller
var id = ele.attr('data-model-id'); // the id that's given to each button in the list
$.get(url + '/' + id, function (data) {
$('#newmodal').find(".modal-content").html(data);
$('#newmodal').modal('show');
});
};
First, your use of EditorFor() makes no sense, and the usage should be just
#Html.EditorFor(x => x.Name, "new { htmlAttributes = new { #class = "form-control col-md-6" } })
Next you script to save the data should be
function btndbsave(obj) {
var ele = $(obj);
var id = ele.attr("data-model-id");
var name = $("#Name]").val();
var phone = $("#Phone").val();
var email = $("#Email").val();
var AjaxVM = { Id: id, Name: name, Phone: phone, Email: email };
$.ajax({
url: '#Url.Action("Edit", "Home")', // don't hard code your url's
dataType: "json",
data: AjaxVM,
type: "POST",
success: function (response) {
.... // see notes below
},
error: function (xhr) {
alert("error");
}
});
};
Note however that you modal should include a <form> and the #Html.ValidationMessageFor() code to give you client side validation along with a submit button so that your script becomes
$('form').submit(function(e) { // or give the form an id attribute and use that
e.preventDefault();
... // make ajax call
});
Next, you controller method need only return a value indicating success or otherwise (along with any error message if applicable), for example
return Json(new { success = true }); // if saved
return Json(new { success = false, message = "...." }); if not saved
Note that adding a ModelStateError makes no sense because you are not returning a view
and then in the ajax call back, you update the <td> elements is successful (or display error if not). In order to do that, include a global javascript variable to store the current row
and change the link that opens the modal to
<a class="edit-record" data-model-id="#item.Id" href="#" ><img src="/UserImages/pencil.png" /></a>
and the script to
var currentrow;
$('.edit-record').click(function() {
currentrow = $(this).closest('tr'); // assign the current row
... // load and display the modal
});
$.ajax({
....
success: function (response) {
if (response.success) {
// Update the current row
var cells = currentrow.find('td');
cells.eq(1).text(name);
cells.eq(2).text(phone);
cells.eq(3).text(email);
} else {
... // oops - display the message in response.message?
}
}
....
}
Note also that there is no need to make an ajax call to load the modal because you already have all the data in the view. Instead, include the html for editing a AjaxVM in the initial view, for example, using
#Html.Partial(""_Edit", new AjaxVM())
then update the values of the inputs when you display the modal
$('.edit-record').click(function() {
currentrow = $(this).closest('tr');
var cells = currentrow.find('td');
$('#Name').val(cells.eq(1).text());
$('#Phone').val(cells.eq(2).text());
$('#Email').val(cells.eq(3).text());
$('#newmodal').modal('show');
});
I have a cascade DropDownList, but in the second dropdown when I post data to controller the valeu property in the object that my action receives is null, and I dont know why.
My controller.
[HttpPost]
public JsonResult ListaEstados(String id)
{
var estados = Util.getEstados(id);
return Json(estados);
}
[HttpPost]
public ActionResult AddCidade(Cidade c)
{
c.Cadastrar(c);
return RedirectToAction("AddCidade");
}
My View
#model Projeto_P1.Models.Cidade
#{
ViewBag.Title = "Cadastro de Cidades";
}
#using (Html.BeginForm("AddCidade", "Geral", FormMethod.Post))
{
<div class="container">
<fieldset>
<div>
#Html.Label("Cidade")
#Html.EditorFor(model => model.Nome)
</div>
<div>
#Html.Label("País")
#Html.DropDownList("Pais", (SelectList)ViewData["paises"], "Selecione", new { id = "PaisID"})
</div>
<div>
#Html.Label("Estado")
#Html.DropDownListFor(model => model.Estado, Enumerable.Empty<SelectListItem>(), "Selecione")
</div>
<br />
<input type="submit" value="Cadastrar" />
</fieldset>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$("#PaisID").change(function () {
$.ajax({
url: "ListaEstados",
type: 'POST',
data: { ID: $(this).val() },
datatype: 'json',
success: function (data) {
var elements = "";
$.each(data, function () {
elements = elements + '<option values="' + this.ID + '">' + this.Nome + '</option>'
})
$('#Estado').empty().attr('disabled', false).append(elements);
}
});
});
});
</script>
Ive solved my problem, there is a S in ajax code, I have´t seen it: elements = elements + '<option values="' + this.ID...
I took it and it worked.
I'm trying to learn MVC and one the things I want to do is submit a form to an action in my controller and this action will return the submitted data. Sounds simple but I've been trying for hours without any success.
my view:
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
my controller:
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
mRep.Add(ajaxComment);
uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
and my js:
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
You don't need to write any client side code to do this, FYI.
To use the ajax methods successfully in MVC, you will need to do the following. Add this key to appsettings in web.config:
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
As well as include the unobtrusive ajax script:
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Then create div container around your form and replace Html.BeginForm with Ajax.BeginForm
<div id="ajaxReplace">
#using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" }))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
</div>
Then in your controller you'll return something like this:
return PartialView(ajaxComment);
This will save you maintaining a script to do this manually and will funnel you into using the framework as intended. It will also help you out with data annotation validation and all of the juicy stuff that goes with it,
I hope this helps in some way.
Try this:
The Model
public class Comment
{
public string CommentText { get; set; }
public DateTime? DateCreated { get; set; }
public long PostId { get; set; }
public string UserName { get; set; }
}
The View and js
#model SubmitMvcForWithJQueryAjax.Models.Comment
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
#Html.EditorFor(m => m.UserName)
</div>
<div class="editor-text">
#Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} )
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.DateCreated)
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.PostId)
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
var serializedForm = $(this).serialize();
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
data: serializedForm,
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
</script>
The Controller
public class CommentController : Controller
{
//
// GET: /Comment/
public ActionResult Index()
{
return View(new Comment());
}
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
//mRep.Add(ajaxComment);
//uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
}
Basically you are passing javascript object literals directly. So, before you pass data to your controller, it must be in JSON format(because you have specified application/json. see your $.ajax call).
SO, you are missing JSON.stringify()
data: JSON.stringify({
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
}),
OR
var someObj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
/// your other code
data: JSON.stringify(someObj),
// your rest of the code
});
Instead of
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
Try
$('form').submit(function () {
var obj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
...,
data: JSON.stringify(obj),
...,
});
return false;
});
You have to convert data to string before sending it to server. and JSON.stringify does that job