ajax post data null in mvc core controller method - ajax

I faced this problem here , but I can not solve it . I searched a lot and tried every solution I found on the similar post . so if there is any help to my case . my part of my app which I found the problem in , first here is my view , I have Categories dropdown when I choose a category I will load the property of that value in a table.
#model Demo.Models.ViewModel.DeviceVM
<form method="post">
<input hidden asp-for="#Model.device.ID" />
<div class="border p-3">
#*putting the page label*#
<div class="row">
<h3 class="text-info pl-3 pb-3">Create Device</h3>
</div>
#*fifth Row => Category List*#
<div class="form-group row">
#*field Label*#
<div class="col-4">
<label asp-for="#Model.device.CategoryID"></label>
</div>
#*field Text*#
<div class="col-8">
<select asp-for="#Model.device.CategoryID" asp-items="#Model.CategoryDropDown" class="form-control"
id="CategoryList">
<option value="">-- Select Category --</option>
</select>
<span asp-validation-for="#Model.device.CategoryID" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label>Category Properties</label>
</div>
<div class="col-8">
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th>Property</th>
<th>Value</th>
</tr>
</thead>
<tbody id="plist">
</tbody>
</table>
</div>
</div>
#*Seventh Row => Buttons*#
<div class="form-group">
<div class="col-8 offset-4 row">
#*Save Button*#
<div class="col">
<input type="submit" value="Save" asp-action="Create" class="btn btn-info w-100" />
</div>
#*Back Button*#
<div class="col">
<a class="btn btn-success w-100" asp-action="Index">Back</a>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
#section Scripts
{
<script>
$(function ()
{
$('#CategoryList').on("change", function () {
var _category = $('#CategoryList').val();
var obj = {CategoryID:_category};
AjaxCall("GetCategoryProperty", JSON.stringify(obj), 'POST').done(function (response) {
console.log(JSON.stringify(obj));
if (response.length > 0)
{
console.log("i'm here ");
}
}).fail(function (error) {
alert(error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
return $.ajax({
url: url,
type: type ,
data: data ,
contentType: 'application/json; charset=utf-8',
dataType:'json'
});
}
</script>
}
here is my Category Model
public class Category
{
[Key]
public int ID { get; set; }
[Required,MaxLength(15),Display(Name ="Category Name")]
public string CatName { get; set; }
public virtual ICollection<Category_Property> categoryprperties {get;set;}
}
here is my Function in the view which always receive 0 in it's parameter
[HttpPost]
public JsonResult GetCategoryProperty([FromBody]int CategoryID)
{
DeviceVM obj = new DeviceVM();
var _CategoryProperty = (from cp in _db.Category_Property
join p in _db.Property on cp.PropertyID equals p.ID
where cp.CategoryID == CategoryID
select new { cp.CategoryID, p.Description, cp.PropertyID });
return Json(_CategoryProperty );
}
I opened the inspect in the browser I it did not reach the message inside the if block because ajax always send 0 for the category id , which I asking for a help to get work.

Two ways you can achieve your requirement.
The first way you can post the id by form like below:
1.Change JSON.stringify(obj) to obj and remove contentType: 'application/json; charset=utf-8',:
$(function ()
{
$('#CategoryList').on("change", function () {
var _category = $('#CategoryList').val();
var obj = {CategoryID:_category};
//change here...
AjaxCall("/home/GetCategoryProperty", obj, 'POST').done(function (response) {
console.log(JSON.stringify(obj));
if (response.length > 0)
{
console.log("i'm here ");
}
}).fail(function (error) {
alert(error.StatusText);
});
});
});
function AjaxCall(url, data, type) {
return $.ajax({
url: url,
type: type ,
data: data ,
//contentType: 'application/json; charset=utf-8',
dataType:'json'
});
}
2.Remove [FromBody] or add [FromForm]:
public class HomeController : Controller
{
[HttpPost]
public JsonResult GetCategoryProperty(int CategoryID)
{
//...
}
}
The second way you can post it by body, you need create a model like below then reserve your js code:
public class Test
{
public int CategoryID { get; set; }
}
Change your action:
public class HomeController : Controller
{
[HttpPost]
public JsonResult GetCategoryProperty([FromBody] TestM model)
{
//...
}
}

Related

how to load data in table and bind the same to view Model class in .net core mvc (without refreshing the page)

I'm trying to add data in table via server but unable to succeed. I tried many things but nothing worked. I'm getting the data from the server but unable to populate that in table.. can someone please help me out?
I'm getting this :
"DataTables warning: table id=particlarsTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"
Let me explain my code first:
(In View)
When I click on "Add New Particular" button, bootstrap modal will popup with input fields, those fields will send to the server then again back to view and populate the table with the same data without refreshing the whole page.
I'm stuck on the last stage, I'm getting the data on UI/View in ajax success handler but unable to load that data in table.
here is my view :
<form class="form-horizontal" method="post" id="createAdHocForm">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label>Select Flat</label>
<select asp-for="AdHocInvoice.FlatRid" asp-items="#(new SelectList(Model.Flats,"FlatRid","FlatNumber"))" class="form-control form-control-sm selectpicker" data-live-search="true">
<option selected disabled value="">Select One</option>
</select>
</div>
</div>
</div>
<table class="table table-sm table-responsive-md nowrap w-100" id="particlarsTable">
<thead class="thead-light">
<tr>
<th>Particulars</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody class="bg-white">
#foreach (var item in Model.AdHocInvoice.FlatInvoiceItems)
{
<tr>
<td>#item.Particular</td>
<td>#item.Amount</td>
<td></td>
</tr>
}
</tbody>
</table>
<button class="btn btn-sm btn-outline-info" type="button" onclick="showParticularForm()">Add New Particular</button>
<hr />
<div class="row text-center">
<button class="btn btn-sm btn-outline-success mx-auto" type="submit">Submit</button>
</div>
</form>
bootstrap modal to fill the table :
<div class="modal fade" id="particularWindow">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Invoice Items</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form class="form-horizontal" method="post" id="particularForm">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label>Enter Particular</label>
<input id="particularName" name="particular" class="form-control form-control-sm" required />
</div>
</div>
<div class="col-md-5">
<label>Amount</label>
<input id="particularAmount" name="amount" class="form-control form-control-sm" required />
</div>
<div class="col-md-2">
<button class="btn btn-sm btn-outline-success mt-4" id="btnParticularSubmit" type="button" onclick="addParticular()">Add</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Scripts:
<link rel="stylesheet" href="~/DataTables/datatables.min.css" />
<script type="text/javascript" src="~/DataTables/datatables.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#particlarsTable').DataTable();
});
function showParticularForm() {
$('#particularWindow').modal('show');
}
function addParticular() {
var particular = $('#particularName').val();
var amount = $('#particularAmount').val();
$.ajax({
url: '/FlatInvoice/AddParticular',
data: 'particular=' + particular + '&amount=' + amount,
success: function (response) {
$('#particlarsTable').DataTable().ajax.reload()
}
});
}
</script>
Action Method on controller:
public JsonResult AddParticular(string particular, decimal amount)
{
_flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems.Add(new FlatInvoiceItem { Particular = particular, Amount = amount });
return Json(_flatInvoiceViewModel);
}
Class/Model:
public class FlatInvoiceItem
{
public Guid FlatInvoiceItemRid { get; set; }
public Guid FlatInvoiceRid { get; set; }
public Guid FundRuleRid { get; set; }
public string Particular { get; set; }
public decimal Amount { get; set; }
}
NOTE: this code is in initial phase, I need that input data on server for further process(will add code later) so don't want to use $.('#table_body_id').append("<tr>..</tr>"); type of code.
1.Firstly,reload() is used to send request back to the method which display the DataTable initially(e.g. name this method Test).
2.Secondly,From your AddParticular method,you just add a data to the list but the lifetime is just one request,so when you reload to Test method,the list still contains the initial data without new data.
Conclusion: I suggest that you could save data to database.And get data from database.
Here is a working demo about how to use DataTabale:
1.Model:
public class Test
{
public int Id { get; set; }
public AdHocInvoice AdHocInvoice { get; set; }
}
public class AdHocInvoice
{
public int Id { get; set; }
public string Name { get; set; }
public List<FlatInvoiceItem> FlatInvoiceItems { get; set; }
}
public class FlatInvoiceItem
{
public int Id { get; set; }
public Guid FlatInvoiceItemRid { get; set; }
public Guid FlatInvoiceRid { get; set; }
public Guid FundRuleRid { get; set; }
public string Particular { get; set; }
public decimal Amount { get; set; }
}
public class ViewModel
{
public string Particular { get; set; }
public decimal Amount { get; set; }
}
2.View:
<form class="form-horizontal" method="post" id="createAdHocForm">
<table class="table table-sm table-responsive-md nowrap w-100" id="particlarsTable">
<thead class="thead-light">
<tr>
<th>Particulars</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
#*<tbody class="bg-white">
#foreach (var item in Model.AdHocInvoice.FlatInvoiceItems)
{
<tr>
<td id="particular">#item.Particular</td>
<td id="amount">#item.Amount</td>
<td></td>
</tr>
}
</tbody>*# //DataTable no need to add this tbody
</table>
<button class="btn btn-sm btn-outline-info" type="button" onclick="showParticularForm()">Add New Particular</button>
<hr />
<div class="row text-center">
<button class="btn btn-sm btn-outline-success mx-auto" type="submit">Submit</button>
</div>
</form>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
//$('#particlarsTable').DataTable();
$('#particlarsTable').DataTable({
ajax: {
type: 'GET',
dataType: 'JSON',
url: '#Url.Action("Test", "Home")',
},
columns: [
{ 'data': 'particular' },
{ 'data': 'amount' }
]
})
});
function showParticularForm() {
$('#particularWindow').modal('show');
}
function addParticular() {
var particular = $('#particularName').val();
var amount = $('#particularAmount').val();
$.ajax({
url: '/Home/AddParticular',
data: 'particular=' + particular + '&amount=' + amount
}).done(function (data) {
$('#particularWindow').modal('hide');
$('#particlarsTable').DataTable().ajax.reload();
});
}
</script>
3.Controller:
public class HomeController : Controller
{
private readonly MyDbContext _context;
public HomeController(MyDbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public JsonResult Test()
{
var _flatInvoiceViewModel = _context.Test.Include(i=>i.AdHocInvoice)
.ThenInclude(a=>a.FlatInvoiceItems).Where(i => i.Id == 1).FirstOrDefault();
var list = new List<ViewModel>();
foreach (var item in _flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems)
{
var model = new ViewModel() { Amount = item.Amount, Particular = item.Particular };
list.Add(model);
}
return Json(new { data = list });
}
public void AddParticular(string particular, decimal amount)
{
var _flatInvoiceViewModel = _context.Test.Include(i => i.AdHocInvoice)
.ThenInclude(a => a.FlatInvoiceItems).Where(i => i.Id == 1).FirstOrDefault();
_flatInvoiceViewModel.AdHocInvoice.FlatInvoiceItems.Add(new FlatInvoiceItem { Particular = particular, Amount = amount });
_context.SaveChanges();
}
4.Result:
Reference:
https://datatables.net/examples/data_sources/ajax.html
https://stackoverflow.com/a/59449895/11398810

How do you connect a POST to a different razor page loaded via AJAX into a modal popup?

Edit: Have marked up where the error in the original code was stopping this from working.
I can find plenty of info and examples of this on MVC, but doesn't seem to apply for Razor Pages?
Simple scenario: I have a page (FooList) showing a list of Foo items. Each has an Edit button. This opens a modal popup with the layout (and data) coming from a second page (FooEdit).
The Edit form appears and populates fine, but I can't work out how to get it to post the data back to the FooEdit code behind?
List page, FooList.cshtml
#page
#model Pages.FooListModel
<table>
#foreach (var item in Model.FooListVM)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a onclick="openModal(#item.ID);">Edit</a>
</td>
</tr>
}
</table>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header border-bottom-0">
<h5 class="modal-title" id="exampleModalLabel">Edit Foo</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form> <---- Edit: ** This shouldn't be here **
<div class="modal-body">
</div>
</form> <---- Edit
</div>
</div>
</div>
<script>
function openModal(i) {
$.get("FooEdit?id="+i,
null,
data => {
$("#editModal").modal("show");
$("#editModal .modal-body").html(data);
});
};
</script>
Code behind, FooList.cshtml.cs
public class FooListModel : PageModel
{
public IList<FooListVM> FooListVM { get; set; }
public void OnGet()
{
FooListVM = new List<FooListVM>
{
new FooListVM { ID = 1, Name = "Foo 1" },
new FooListVM { ID = 2, Name = "Foo2" }
};
}
}
public class FooListVM
{
public int ID { get; set; }
public string Name { get; set; }
}
Second page for the popup, FooEdit.cshtml
#page
#model Pages.FooEditModel
#(Layout=null)
<form method="post">
<input asp-for="FooEditVM.Name" class="form-control" /><br />
<input asp-for="FooEditVM.Stuff1" class="form-control" /><br />
<input asp-for="FooEditVM.Stuff2" class="form-control" /><br />
<input type="submit" value="Save"/>
</form>
And the code behind for the popup, FooEdit.cshtml.cs
public class FooEditModel : PageModel
{
[BindProperty]
public FooEditVM FooEditVM { get; set; }
public void OnGet(int id)
{
FooEditVM = new FooEditVM
{
Name = $"This is item {id}",
Stuff1 = "Stuff1",
Stuff2 = "Stuff2"
};
}
public void OnPost(int id)
{
// How do we get to here???
var a = FooEditVM.Name;
}
}
public class FooEditVM
{
public string Name { get; set; }
public string Stuff1 { get; set; }
public string Stuff2 { get; set; }
}
I've been through all the MS Tutorial stuff on Asp.net Core 2.2, but it doesn't seem to cover this.
Also as a side question, although it works, is there a "ASP helper tag" way of doing the ajax bit?
Have realised the problem was the 'form' tag in the Modal Dialog markup that was clashing the 'form' tag from the partial page. Removing it fixed everything using:
In FooEdit.cshtml
<form id="editForm" asp-page="FooEdit">
. . .
</form>
In FooEdit.cshtml.cs
public void OnPost()
{
// Fires in here
}
I'm pretty sure the fooedit page is going to need some jQuery to handle this.
See below for what I would do in the fooedit page.
#page
#model Pages.FooEditModel
#(Layout=null)
<form id=fooedit method="post" action="FooEdit">
<input asp-for="FooEditVM.Name" class="form-control" /><br />
<input asp-for="FooEditVM.Stuff1" class="form-control" /><br />
<input asp-for="FooEditVM.Stuff2" class="form-control" /><br />
<input type="submit" value="Save"/>
</form>
<SCRIPT language="JavaScript" type="text/Javascript">
<!--
$(document).ready(function(e) {
$("#fooedit").submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#editModal.modal-body").html(returnhtml);
}
});
});
});
</SCRIPT>

Deleting using Entity Framework and calling controller method in ajax

I have been trying to create a delete button in mvc using json to call the delete method in my controller but so far its not working.
I did trap the error alert in the script and the success section is not registering a thing, I need help well here is my view, that picks data from SQL Server using Entity Framework 5.1.
I am working with a table called Departments and it has two columns, DepartmentId and DepartmentName.
<div class="container" style="width:40%; margin-top:2%;">
<hr />
<table class="table-responsive">
<tr>
<th>Deprtment Name</th>
<th></th>
</tr>
<tbody>
#if(ViewBag.RowDepartmentList != null)
{
foreach(var item in ViewBag.RowDepartmentList)
{
<tr id="row_#item.DepartmentId">
<td>#item.DepartmentId</td>
<td>#item.DepartmentName</td>
<td><a href="#" class="btn btn-danger" onclick="ConfirmDelete(#item.DepartmentId)">
<i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
}
}
</tbody>
</table>
<input type="hidden" id="HiddenDepartmentId" />
</div>
I added a hidden attribute to capture the DepartmentId, the form too has a delete button that first calls a delete dialog modal.
My DELETE dialog modal code:
<div class="modal fade" id="mymodal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" style="width:350px;">
<div class="modal-content">
<div class=" modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="close">
<span aria-hidden="true">x</span>
</button>
<h3 class="modal-title">Delete record</h3>
</div>
<div class="modal-body">
<h4>Are you sure you want to delete this?</h4>
</div>
<div class="modal-footer">
Cancel
Delete
</div>
</div>
</div>
And this is what my controller looks like:
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult DepartmentIndex()
{
MVCTutorialEntities2 db = new MVCTutorialEntities2();
List<EmployeeViewModel> emlist = db.Departments.Where(x => x.IsDeleted == 0).Select(x => new EmployeeViewModel {DepartmentId=x.Departmentid, DepartmentName = x.DepartmentName }).ToList();
ViewBag.RowDepartmentList = emlist;
return View();
}
// the delete function
[HttpPost]
public JsonResult DelDepartment(int depId)
{
MVCTutorialEntities2 db = new MVCTutorialEntities2();
bool result = false;
Department dep = db.Departments.SingleOrDefault(x => x.Departmentid == depId);
if (dep != null)
{
db.Departments.Remove(dep); // I don't know why this is not deleting .... the table is not cascaded
db.SaveChanges();
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
// now my script is all here that calls the
<script>
var ConfirmDelete = function (DepartmentId) {
$("#HiddenDepartmentId").val(DepartmentId);
$("#mymodal").modal("show");
}
var DelDepartment = function ()
{
var depId = $("#HiddenDepartmentId").val();
$.ajax({
type: 'POST',
url: 'Employee/DelDepartment',
data: { DepartmentId: depId },
success: function (result) {$("#mymodal").modal("hide"); },
error: function (result) { alert(result); $("#mymodal").modal("hide"); } // only the error section resturns a message of [object] of [object]
});
}
</script>
Trying so hard to learn this language ... and if so, is there any way I can just use razor and call the delete function from the
#using (Html.BeginForm("", "",FormMethod.POST)) ?
function?
data: { DepartmentId: depId } needs to be
data: { depId: depId } because the left JS parameter name has to match up with the parameter name on the controller side.
Or you may need to do: data: JSON.stringify({ depId: depId })
If that doesn't work, you can do url: 'Employee/DelDepartment?depId=' + deptId and just get rid of the data property altogether.

Ajax Post: ASP.NET MVC action is receiving empty object

I have this form:
#model CupCakeUI.Models.CupCakeEditViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFrm" }))
{
<div class="form-group">
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
<input type="text" id="Name" name="Name" value="#Model.Name" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model)
</div>
<div class="editor-field">
<input type="text" id="Price" name="Price" value="#Model.Price" />
</div>
<div class="col-md-offset-2 col-md-10">
<input type="button" id="btnCreate" value="Create" class="btn btn-default" />
</div>
</div>
}
I am trying to use ajax post to send data to the Action Method, however its always receiving empty object. I have done that several times in the past, and now i tried different ways which not working, The code:
$(document).ready(function () {
$("#btnCreate").click(function () {
var name = $("#Name").val();
var price = $("#Price").val();
var cupCakeEditModel = { "CupCakeId": 0, "Name": name, "Price": price };
var json = JSON.stringify(cupCakeEditModel);
$.ajax({
type: 'POST',
url: "/CupCake/Create",
data: JSON.stringify(cupCakeEditModel),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
})
})
Its showing this in the console when logging:
This is the Action Method and Class used:
[HttpPost]
public JsonResult Create (CupCakeUI.Models.CupCakeEditViewModel cupCakeEditModel)
{
var cupCake =
CupCakeData.Save(cupCakeEditModel);
return Json("cupCake",
JsonRequestBehavior.AllowGet);
}
This the class:
public class CupCakeEditViewModel
{
public int CupCakeId;
[Display(Name = "CupCake Name")]
public string Name;
public string Price;
}
I have also used this, but not working:
$("#btnCreate").click(function () {
var cupCakeEditModel =
$("#createFrm").serialize();
$.ajax({
url: "/CupCake/Create",
type: "POST",
data: cupCakeEditModel,
success: function (response) {
alert("Success");
},
error: function (response) {
}
});
})
And several answers i found on the forum, but it seems something weird!
You model contains only fields, and the DefaultModelBinder does not bind fields, only properties. Change the model to
public class CupCakeEditViewModel
{
public int CupCakeId { get; set; }
[Display(Name = "CupCake Name")]
public string Name { get; set; }
public string Price { get; set; }
}

Umbraco BlogComment Create Ajax

Hello im trying to post my blog comments the function works. but the whole site refreshes inside the div, i tried playing around with the partialview in the controller but im not sure what to do can anybody here point me in the right directtion, i want div to refresh with ajax request not the whole site intro the div.
<!-- Blog Comments -->
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
#if (Members.GetCurrentLoginStatus().IsLoggedIn)
{
using (Html.BeginUmbracoForm("CreateComment", "CommentSurface", FormMethod.Post, new { #id = "comment-form" }))
{
// use this where every display profile image is needed
var user = User.Identity.Name;
var imgUrl = Url.Content("~/media/profileimage/" + user.Replace(".", "") + ".png");
<input name="CommentOwner" type="text" value="#Members.GetCurrentMember().Name" class="form-control hidden" readonly="readonly" />
<input name="ownerid" type="text" value="#Members.GetCurrentMember().Id" class="form-control hidden" readonly="readonly" />
<div class="form-group">
<textarea name="Message" rows="3" placeholder="Type your message here" class="form-control"></textarea>
</div>
<input name="profileimage" type="text" value="#imgUrl" class="hidden" readonly="readonly" />
<button type="submit" class="btn btn-primary">Submit</button>
}
}
else
{
<p> You are not logged in Register here</p>
}
</div>
<hr>
<!-- Posted Comments -->
<div class="blog-comments">
#Html.Partial("_BlogComments")
</div>
<!-- Comment -->
#section scripts {
<script>
$(function () {
// Find the form with id='well-form'
$('#comment-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
$(".blog-comments").html(data);
},
error: function (result) {
alert('Comment was not successful!');
}
});
// return false to cancel the form post
// since javascript will perform it with ajax
return false;
});
});
</script>
}
</div>
SurfaceController:
public class CommentSurfaceController : SurfaceController
{
[HttpPost, ValidateInput(false)]
public ActionResult CreateComment(CommentViewModel model)
//public PartialViewResult CreateComment(CommentViewModel model)
{
if (!ModelState.IsValid)
{
return CurrentUmbracoPage();
}
var contentService = Services.ContentService;
var newContent = contentService.CreateContent(DateTime.Now.ToShortDateString() + " " + model.CommentOwner, UmbracoContext.PageId.Value, "BlogComment");
newContent.SetValue("CommentOwner", model.CommentOwner);
newContent.SetValue("Message", model.Message);
newContent.SetValue("profileimage", model.profileimage);
newContent.SetValue("ownerid", model.ownerid);
//Change .Save if u want to allow the content before publish
contentService.SaveAndPublishWithStatus(newContent);
return RedirectToCurrentUmbracoPage();
//return PartialView("BlogComments", model);
}
public ActionResult DeleteComment(int commentid)
{
var service = ApplicationContext.Current.Services.ContentService;
var content = service.GetById(commentid);
service.Delete(content);
return RedirectToCurrentUmbracoPage();
}
}
Partial View:
#foreach (var item in Model.Content.Children().OrderByDescending(m => m.CreateDate))
{
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" width="64" src="#item.GetPropertyValue("profileimage")" alt="profile image">
</a>
<div class="media-body">
<h4 class="media-heading">
#item.GetPropertyValue("CommentOwner")
<small>#item.CreateDate</small>
</h4>
#item.GetPropertyValue("Message")
</div>
#item.Id
</div>
if (Members.GetCurrentLoginStatus().IsLoggedIn)
{
if (#Members.GetCurrentMember().Id.ToString() == item.GetPropertyValue("ownerid").ToString())
{
#Html.ActionLink("Delete", "DeleteComment", "CommentSurface", new { commentid = item.Id }, null)
}
else
{
#*<p> not ur comment</p>*#
}
}
else
{
//blank cant delete comment if not logged in
}
}
The problem is that UmbracoSurfaceController is loosing his context if you are not rendering the complete page.
If you work with ajax, you should not render out html and post this back. Only POST the data and update your layout in javascript when you get a 200 (ok) back from the server.
To do so, use the UmbracoApiController. This is a WebApi controller allowing you to send back json (or xml) serialized data.
More information about the UmbracoApiController can be found in the documentation.

Resources