How to remove data from view run-time? - javascript

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
In below image, we can see the comment box which is called run-time for employee index view.
problem is, when user delete comment, its get deleted from DB but how to remove it from the screen without redirect to any page ?
I wan to remove that deleted comment div tag smoothly...
Please see the image...
my code is...
#model IEnumerable<CRMEntities.Comment>
#{
<div class="ParentBlock">
#foreach (var item in Model)
{
<div class="OwnerClass" id="OwnerName" data-comment-id="#item.Id">
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName"><button type="button" class="deleteComment">Delete</button></span>
<p class="CommentP">
#Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
<a class="Delete222" style="cursor:move;display:none;">DeleteNew</a>
<br />
</div>
}
<p class="p12">
</p>
</div>
<p id="ClassPara" class="ShowComments" onclick="chkToggle()">Show All Comments</p>
}
#Html.TextArea("Comment", "", 5, 80, "asdsd")
<input type="button" value="Add Comment" id="AddCommentButton"/>
<input type="button" value="Clear" onclick="clearText()"/>
<br />
</body>
</html>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".deleteComment").click(function () {
alert("asd");
var commentBlock = $(this).parent('.OwnerClass');
commentBlock.hide('slow')
});
});
$(document).ready(function () {
$('.OwnerClass').hover(function () {
$('.Delete222', this).show();
}, function () {
$('.Delete222').hide();
});
});
</script>

Instead of generating action link, place there button or . Bind JavaScript function to click event on this button, in this function make ajax call to action that deletes comment from db and use Jquery to hide proper div.
<span class="EmpName"><button type="button" class="deleteComment">Delete</button></span>
JavaScript:
$('.deleteComment').click(function ()
{
var commentBlock = $(this).parent('.ParentBlock');
$.ajax({
type: 'post',
url: '/Comment/DeleteComment',
dataType: 'json',
data:
{
commentId: getCommentId(commentBlock )
},
success: function (data) {
commentBlock.hide('slow')
}
});
});
UPDATE:
Update due to question update and comments below this answer:
$(document).ready(function () {
$(".deleteComment").click(function () {
var commentBlock = $(this).parent('.OwnerClass');
$.ajax({
type: 'post',
url: '/Comment/DeleteComment',
dataType: 'json',
data:
{
commentId: commentBlock.attr('data-comment-id')
},
success: function (data) {
commentBlock.hide('slow')
}
});
});
});

Related

How to get Ajax form to work in asp.net core

net core and I'm building a to do list app to learn but iv hit a road block trying to add an item to a to do list with out refreshing the page.
With my current setup the controller method to add a todo item to DB and a script to get refresh the html on page are called on form submit but the html is updated before item is added to DB.
Any suggestions on how to fix this or what is the best way to go about doing this would be greatly appreciated.
My Div for Table:
<div id="tableDiv"></div>
My Input form:
<div id="addTodoForm">
<form asp-action="AddToDoForm" method="post" data-ajax="true" >
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
</form>
</div>
My Script To update html (has a time out function as a temporary fix to this issue)
<script>
$("#addTodoForm").submit(function()
{
setTimeout(function(){
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
})
}, 500);
})
</script>
My method to add Item to DB:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
if (ModelState.IsValid)
{
string currentUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
IdentityUser currentUser = _context.Users.FirstOrDefault(x => x.Id == currentUserId);
toDo.User = currentUser;
toDo.Status = false;
_context.Add(toDo);
await _context.SaveChangesAsync();
}
return BuildToDoTable();
}
Not sure what is your whole code, here is a simple working demo about how to post data to backend and display the data from backend without refreshing:
View:
#model ToDo
<div >
<form method="post" id="addTodoForm">
<input asp-for="Id" class="form-control "/>
<input asp-for="Item" class="form-control " placeholder="Add To Do Item.." />
//focus here...it is type of button and add an onclick event here.....
<input type="button" value="Create" class="btn btn-primary" onclick="PostData()" />
</form>
</div>
<div id="tableDiv"></div>
#section Scripts {
<script>
function PostData() {
$.ajax({
type: "POST",
data: $("#addTodoForm").serialize(), //using this way to get the form data
url: '/Home/AddToDoForm',
success: function (result) {
$('#tableDiv').html(result);
}
})
}
</script>
}
Controller:
public class HomeController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddToDoForm([Bind("Id,Item")] ToDo toDo)
{
return PartialView("Partial", toDo);
}
}
Partial.cshtml(jsut a easy view for testing):
#model ToDo
#Model.Item //display the data
You can use e.preventDefault() which prevents the default behavior of submitting your form (refresh the page).
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
})
</script>
use this code:
<script>
$("#addTodoForm").submit(function(e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/ToDos/BuildToDoTable',
success: function (result) {
$('#tableDiv').html(result);
}
});
location.reload();
})
</script>

Call Action Method on button click ASP.NET MVC

I am trying to get user input in button click.
When user insert number and press Check, it needs to return xml data type.
So in my controller I create function which will return a data for passing ID
[ResponseType(typeof(AKONTA))]
public IHttpActionResult GetAKONTA(string id)
{
AKONTA aKONTA = db.AKONTAS.Find(id);
if (aKONTA == null)
{
return BadRequest("Ne postoji A_KONTO pod tim rednim brojem");
}
return Ok(aKONTA);
}
And In my View I have following
<br /><br />
<form>
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<a asp-action="Index" class="btn btn-primary" id="aKonto" action="#Url.Action("GetAKONTA", "Akontas")">Provjeri</a>
</div>
</form>
And I want to create in btn click when user pass ID it needs to return XML data format.
SO far I create a JS function, but I don't know JavaScript and don't know the logic how to pass Controller Action Result to JS.
<script>
$(document).ready(function () {
$('#aKonto').click(function () {
document.getElementById("aKonto").onclick = function () {GetAKONTA()};;
});
});
</script>
If someone can help me I would be very thankful.
Cheers !
UPDATE
function aKontoSubmit() {
$.ajax({
type: "GET",
url: 'api/Akontas',
//data: { id: id },
dataType: "xml",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
**routeConfig**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AkontasWebApi
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Add Reference of Jquery, to try the ajax call method.
function aKontoSubmit() {
$.ajax({
type: "POST",
url: '/Akontas/GetAKONTA',
data: $('form').serialize(),
dataType: "json",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Error while inserting data");
}
});
}
Change you Link Code as Below
<a asp-action="Index" class="btn btn-primary" id="aKonto" onClick='return aKontoSubmit() '>Provjeri</a>
Or Else You Can try if you are using ASP.Net MVC Core Development
<form asp-action="GetAKONTA" asp-controller="Akontas" method="post">
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<input class="btn btn-primary" id="aKonto" type = "submit" value = "Provjeri" />
</div>
</form>
After a couple hours of debugging and searching I found that I forget to put
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
This is location where should redirect if item exsist in database
And URL call need to be modified as well
URL: "/api/Akontas/GetAKONTA",
function aKontoSubmit() {
$.ajax({
type: "GET",
URL: "/api/Akontas/GetAKONTA",
data: { id: $('#AkontasId').val() },
contentType: "data/xml; charset=utf-8",
success: function (result) {
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}

Post Data from MCV is not calling JS function

Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);

Ajax executing different form on submit

I've created two forms and assigned different submit button IDs. But ajax is executing single form every time even if I execute different button for different ajax call. Following is the code:
Form1.
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#monthlyForm").submit();
$.ajax({
url: '/monthlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton').on('click', function (e) {
handler.open({
name:'Monthly',
description:'Monthly Package',
amount:1450
});
e.preventDefault();
});
$(window).on('popstate', function () {
handler.close();
});
</script>
Form2:
<form action='/cancelannual' method='post'><a href="/cancelannual">
<input class='btn genz-light-red'style=";width:50%; background:#FF1744; height:33px;color:white;"type="submit" value="Cancel" /></a></form>
<!-- Custom Button -->
<form id="yearlyForm" action="/yearlycharged" method="post" >
<div class="form-group">
<input type="hidden" id="stripeToken" name="stripeToken" />
<input type="hidden" id="stripeEmail" name="stripeEmail" />
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton1">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#yearlyForm").submit();
$.ajax({
url: '/yearlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton1').on('click', function (e) {
handler.open({
name:'Yearly',
description:'Yearly Package',
amount:9500
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function () {
handler.close();
});
</script>
If I click on "customButton" it processes yearly subscription if I click on "customButton1" still it processes yearly subscription instead of monthly. Surprisingly when form popups it has the monthly values in it. But after processing database shows Yearly package processed. In my python/flask code without ajax I can process both packages seperately so the problem is not in my views it lies somewhere in Ajax. Please advise
You have two var handler declarations in the global scope - the second hides the first. Name them differently or wrap both code fragments in separate $(document).ready(function() {...});

Open Javascript Id on a new window

Am trying to open an id on a new window, this is my code:
<script type="text/javascript">
$(document).ready(function () {
$('.myButton').click(function () {
$.ajax({
type: "GET",
url: $(this).parent().data("url"),
data: { callNumber: $(this).parent().data("callno") },
success: function (data) {
$("#CallDetail").html(data);
},
});
});
});
</script>
When i click .myButton class it opens the id:
<div id="CallDetail"></div>
thats located on the home page.
What i need is to open on a new window, i have tried doing this via the link :
<div data-callno='#parts.Call_Num' data-url="#Url.Action("GetCallInfo", "CallHandling" , new {target = "_blank"})">
<div class="myButton toolbarIcon">
<div class="toolbarIconText">View</div>
</div>
But no luck, at the moment it just opens in the same page i am doing this, the problem is am getting data called in the JavaScript so its trickier then i imagined. any ideas?
You can use jQuery's .find to search the returned HTML for a selector:
$(document).ready(function () {
$('.myButton').click(function () {
$.ajax({
type: "GET",
url: $(this).parent().data("url"),
data: { callNumber: $(this).parent().data("callno") },
success: function (data) {
$(data).find('#CallDetail');
},
});
});
});

Categories