Deleting using Entity Framework and calling controller method in ajax - 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.

Related

Is there a way to NOT refresh the Page after Updating the data? Laravel 8 and Vue

How can I not refresh or reload the page after updating the data?
I am using Modal to edit the data but the problem is the page still refresh after saving it, is there another way around to fix this concern?
<button class="btn btn-warning" #click="edit(item)"><i class="fa fa-edit"></i></button>
Modal:
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Employee Edit</h5>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" v-model="formEdit.name">
</div>
......
Script: (edit is used to show the data and update is used to update the data)
edit(item){
const vm = this;
vm.formEdit.name = item.name;
vm.formEdit.address = item.address;
vm.formEdit.position = item.position;
this.selectedId = item.id;
$('#editModal').modal('show');
},
update(){
const vm = this;
axios.put(`/employees/${vm.selectedId}`, this.formEdit)
.then(function (response){
alert('Employee Updated')
location.reload();
})
.catch(function (error){
console.log(error);
});
}
This is for Laravel 8 and Vue
employees component:
props: ['employee'],
data() {
return {
employeeList: this.employee,
form:{
name: null,
address: null,
position: null
},
formEdit:{
name: null,
address: null,
position: null
},
selectedId: null
}
}
Please next time add all relevant code to let us know what are you trying to achieve.
First of all, please note that data provided from props should not be mutated because of an anti-pattern. Said that you have to create a deep copy within your component in order to change its content.
Assuming that you are working in just 1 component, where you have your table listing all employees, you can do something like this.
<template>
<div>
<table>
<tr v-for="item in employeeList" :key="item.id">
<td>name: {{ item.name }}</td>
<td>address : {{ item.address }}</td>
<td>position : {{ item.position }}</td>
<td><button class="btn btn-warning" #click="edit(item)"><i class="fa fa-edit"></i></button></td>
</tr>
</table>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Employee Edit</h5>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" v-model="form.name">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success" #click="update()">Save</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
employee: Array
},
data: () => ({
employeeList: [],
form: {}
}),
mounted () {
// Since changing a props is anti-pattern, we use a local data which can be manipulated
this.employeeList = [...this.employee]
},
methods: {
edit(item){
// Assign the clicked item to form data
this.form = item
$('#editModal').modal('show')
},
update(){
axios.put(`/employees/${this.form.id}`, this.form)
.then(function (response){
alert('Employee Updated')
// Find the employee index in employeeList array
const updatedEmployee = response.data
const index = this.employeeList.findIndex(x => x.id === updatedEmployee.id)
// If employee is found, then proceed to update the array object by using ES6 spread operator
if (index !== -1) {
this.employeeList = [...this.employeeList.slice(0, index), { ...updatedEmployee}, ...this.employeeList.slice(index + 1)]
}
})
.catch(function (error){
console.log(error)
})
}
}
}
</script>
Code is self-explanatory, but just in case I will clarify a little bit:
Because we can not mutate the props employee, we copy the array to local data by using the ES6 spread operator in mounted() hook.
When you click the button to edit an employee, you assign the item to the form data. Now you have the form with all employee data to be shown/changed anywhere.
Once success API response, since you are updating, you look for the array object and replace the whole array to avoid reactivity issues. In case you are adding a new one, you just can push it by doing this.employeeList.push(updatedEmployee)
EDIT: please note that the above code is a suggestion about how to work with a clean code.
Anyway, right to your question, you can update your array in your axios response by doing
.then(function (response){
alert('Employee Updated')
// Find the employee index in employeeList array
const updatedEmployee = response.data
const index = this.employeeList.findIndex(x => x.id === updatedEmployee.id)
// If employee is found, then proceed to update the array object by using ES6 spread operator
if (index !== -1) {
this.employeeList = [...this.employeeList.slice(0, index), { ...updatedEmployee}, ...this.employeeList.slice(index + 1)]
}
})
.catch(function (error){
console.log(error)
})
during update remove
location.reload();
and add the below code
$('#editModal').modal('hide');
To display data follow the procedure, update data receive from response:
updateStudent(){
axios.put('update_student',{
id:this.id,
name:this.editname,
email:this.editemail,
phone:this.editphone,
})
.then(response=>console.log(response));
axios.get('all_students')
.then(response => {
this.data = response.data;
});
},
You can display the updated data like the below code:
<tr v-for="row in data">
<th scope="row">1</th>
<td>{{ row.name }}</td>
</tr>
Let's create an item in data to assign the value we get from props. Next, let's assign props data to the created element.
The page refresh issue will be resolved.

ajax post data null in mvc core controller method

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)
{
//...
}
}

Validation error message not displayed in Asp.Net Core 2 MVC partial view

I have an index page with a list of "workbooks" titles and for each workbook, there is a "share" button. When pressing the button a bootstrap model (i.e. dialog) appears which displays the title of the workbook and a textarea allowing the user to type in a sharees email addresses.
When the user presses on the "share" button, I am calling a javascript function which calls a controller action that returns a partial view containing the modal dialog with a form inside it. The problem is that after pressing the submit button (i.e. "Share") there are no validation errors being shown to the user and I am not sure why that is. Could anyone provide some ideas, please?
That is my main (index.cshtml) page:
#model DNAAnalysisCore.Models.WorkBookModel
#{
}
#section BodyFill
{
<script type="text/javascript">
function showSharingView(title) {
var url = "#Url.Action("ShowShareDialog", "Home")" + "?workbookTitle=" + encodeURI(title);
$('#shareFormContainer').load(url,
function() {
$('#shareFormModal').modal("show");
});
}
function hideSharingView() {
$('#shareFormModal').modal("hide");
}
</script>
<div id="shareFormContainer" >
<!--PLACEHOLDER FOR SHARE DIALOG -->
</div>
<div class="workbook-container">
<table class="table">
<tbody>
#foreach (var workbook in Model.Workbooks)
{
<tr>
<td>#Html.ActionLink(workbook.Name, "Open", "OpenAnalytics", new {id = Model.Id, workbook = workbook.Name})</td>
<td>
<button title="Share" class="share-button" onclick='showSharingView("#workbook.Name")'> </button>
</td>
</tr>
}
</tbody>
</table>
</div>
}
That is my Controller:
public class HomeController : Controller
{
[HttpGet]
public IActionResult ShowShareDialog(string workbookTitle)
{
var shareModel = new ShareModel
{
Title = workbookTitle
};
return PartialView("_ShareView", shareModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ShareWorkbook(string emails, string title)
{
var share = new ShareModel
{
Emails = emails
};
// TODO EMAIL THE SHARED WORKBOOK using the 'title' of the workbook and the 'email' string value
// return no content to avoid page refresh
return NoContent();
}
}
This is my partial view/modal dialog (_ShareView):
#using DNAAnalysisCore.Resources
#model DNAAnalysisCore.Models.ShareModel
<!-- Modal -->
<div class="modal fade" id="shareFormModal" role="dialog">
<div class="modal-dialog modal-md">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Share Workbook - #Model.Title</h4>
</div>
#using (Html.BeginForm("ShareWorkbook", "Home", FormMethod.Post))
{
<div class="modal-body">
<label>#BaseLanguage.Share_workbook_Instruction_text</label>
<div class="form-group">
<textarea class="form-control" asp-for="Emails" rows="4" cols="50" placeholder="#BaseLanguage.ShareDialogPlaceholder"></textarea>
#* TODO add client-side validation using jquery.validate.unobtrusive.js. See US268276 *#
<span asp-validation-for="Emails" class="text-danger"></span>
</div>
<input asp-for="Title" />
</div>
<div class="modal-footer">
<button type="submit" onclick="hideSharingView()" class="btn btn-primary">Share</button>
<button id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
}
</div>
</div>
</div>
#section Scripts {
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
This is my ShareModel:
public class ShareModel
{
[HiddenInput]
public string Title { get; set; }
[Required]
public string Emails { get; set; }
}
The form is not added to the page when the page loads, the unobtrusive validation will not pick it up.A simple solution is to use $.validator.unobtrusive.parse("#id-of-the-form");.Refer to here.
1.Add id to your form in _ShareView partial view:
#using (Html.BeginForm("ShareWorkbook", "Home", FormMethod.Post,new { #id="partialform"}))
2.Introduce validation file _ValidationScriptsPartial.cshtml into main page(Index.cshtml) and manually register the form with the unobtrusive validation.
#section Scripts
{
#await Html.PartialAsync("_ValidationScriptsPartial")
<script type="text/javascript">
function showSharingView(title) {
var url = "#Url.Action("ShowShareDialog", "Home")" + "?workbookTitle=" + encodeURI(title);
$('#shareFormContainer').load(url,
function() {
$('#shareFormModal').modal("show");
$.validator.unobtrusive.parse("#partialform");
});
}
function hideSharingView() {
$('#shareFormModal').modal("hide");
}
</script>
}

AJAX Model Validation with Partial View

I have a partial view, which is a login that functions as a popup. All I want to do is have my model do the validation (server side) and return any errors via AJAX. The code below returns the partial view only with the errors. I want my action result to not return a a view, but only the errors. In old ASP.NET, this would be a Partial Post back. I am not sure how to accomplish this in MVC.
Here is the Model
public class LoginModel
{
[Required]
public String Email { get; set; }
[Required]
[DataType(DataType.Password)]
public String Password { get; set; }
}
Here is the Partial View
#model MySite.Models.LoginModel
#using (Ajax.BeginForm("Authenticate", "Account", null, new AjaxOptions { OnFailure = "error" }, new { id = "LoginForm" }))
{
<div class="modal-body" id="LoginPopupDialogMessage">
The page you have requested requires you to login. Please enter your credentials and choose your country:
<br />
<br />
<div class="row">
<div class="form-group col-lg-offset-2 col-lg-8">
<label>Email Address</label>
#Html.TextBoxFor(u => u.Email, new { #class = "form-control input-lg input-sm", id = "Email", name = "Email" })
#Html.ValidationMessageFor(u => u.Email)
</div>
</div>
<div class="row">
<div class="form-group col-lg-offset-2 col-lg-8 ">
<label>Password</label>
#Html.PasswordFor(u => u.Password, new { #class = "form-control input-lg input-sm", name = "Password" })
#Html.ValidationMessageFor(u => u.Password)
</div>
</div>
<div style="text-align: center; padding-top: 20px;" class="ImageGroup">
<button name="companyCode" value="LB_US" class="btn-link" type="submit">
<img src="../../WebContent/Images/icon-flag-usa.png" />
</button>
<button name="companyCode" value="LB_CA" class="btn-link" type="submit">
<img src="../../WebContent/Images/icon-flag-canada.png" />
</button>
<button name="companyCode" value="LB_EU" class="btn-link" type="submit">
<img src="../../WebContent/Images/icon-flag-europe.png" />
</button>
</div>
</div>
}
I call the parial view from _layout.cshtml.
<div class="modal fade" id="LoginPopupDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header" style="background: #e7e3e7; color:#000;">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color:#000;">
<span aria-hidden="true">×</span>
</button>
<div class="modal-title" id="LoginPopupDialogHeader">Please Login</div>
</div>
#Html.Action("Login", "Account")
</div>
</div>
</div>
My Controller Action:
[HttpPost]
[Route("account/authenticate")]
public ActionResult Authenticate(String companyCode, LoginModel model)
{
if (!ModelState.IsValid)
{
// ??
}
return PartialView("Login", model);
}
Since your code is doing an ajax form submission for the login, you should try to return a JSON response from the server. If model validation fails, you may read the validation errors from the model state dictionary and store that in a collection of strings (error messages) and return that as part of the json response. If model validation passes, you can continue executing your code to verify the login credentials and if those looks good, send back a json response with the next url for the user (to which we can redirect the user).
[HttpPost]
public ActionResult Authenticate(String companyCode, LoginModel model)
{
if (!ModelState.IsValid)
{
var errors = ViewData.ModelState.Values
.SelectMany(x => x.Errors.Select(c => c.ErrorMessage));
return Json(new { Status = "Error", Errors = errors });
}
//to do :Verify login, if good, return the below respose
var url=new UrlHelper(Request.RequestContext);
var newUrl = url.Action("About");
return Json(new { Status="Success", Url = newUrl});
}
Now in your view, you may specify a OnSuccess handler as part of the AjaxOptions. This will be a javascript object to which the json response from the server will come. We basicallly need to check the Status property value and do the appropriate things.
new AjaxOptions { OnFailure = "error" , OnSuccess="loginDone"}
The below implementation of loginDone simply alerts the error messages. You can update it to show it as part of the DOM.
function loginDone(d) {
if (d.Status === "Success") {
window.location.href = d.Url;
} else {
$.each(d.Errors,function(a, b) {
alert(b);
});
}
}
You may also consider enabling the unobtrusive client side validation which does the client side validation before trying to make a call to server. This will also show the error messages in the validation error spans (same as the normal mvc model validation does)

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