How refresh a view in MVC - asp.net-mvc

I have _LayoutOnecs.html file and View Loads with in it renderbody and displays list of records in table. in one of table column i have a Delete icon on click of it goes to controller and deletes record from database once the record is deleted the view should be refreshed so i returned the action to controller which fetches all the records
public ActionResult GetAdvertisementDetails()
{
var advertisementList = new AdvertisementManager().GetAdvertisementDetails();
return View("AdvertisementDetails", advertisementList);
}
public ActionResult DeleteAdvertisementDetails(int id)
{
new AdvertisementManager().DeleteAdvertisementDetails(id);
return RedirectToAction("GetAdvertisementDetails", "Advertisement");
}
once Delete is done it is going to GetAdvertisementcontroller and return view but the Deleted record sits there in table if i Refresh the page by pressing F5 the record is removed from table.
How do i Refresh automatically when the record is deleted
View Code
<div class="col-md-12 main_table">
<div class="table-responsive">
<table class="table" id="hom_table">
<tr>
<th>Advertisement Name</th>
<th>Link</th>
<th>Start Date</th>
<th>End Date</th>
<th width="100">Action</th>
</tr>
#foreach (var advertisements in Model)
{
<tr>
<td> #advertisements.Description</td>
<td> #advertisements.ImageUrl</td>
<td> #advertisements.StartDate</td>
<td> #advertisements.EndDate</td>
<td>
<a onclick="EditadvertisementDetails(#advertisements.AdvertisementId)">
<i class=" pull_Advt_details tbl_edit_btn fa fa-edit Editbutton"></i>
</a>
<a id="Deladvertisement" onclick="Deleteadvertisement(#advertisements.AdvertisementId)" >
<i class="tbl_del_btn fa fa-trash"></i>
</a>
</td>
</tr>
}
</table>
</div>
<!-- Responsive main table Ends -->
</div>

Ajax calls stay on the same page. Your use of return RedirectToAction("GetAdvertisementDetails", "Advertisement"); in the controller method is ignored. Its also unnecessary to redirect since you can just remove the row from the table
Modify the html to (note remove the id attribute which is generating invalid html):
<a class="delete" data-id="#advertisements.AdvertisementId>
<i class="tbl_del_btn fa fa-trash"></i>
</a>
and use the following script to call the controller method and remove the row
var url = '#Url.Action("DeleteAdvertisementDetails", "Advertisement")';
$('.delete').click(function() {
var row = $(this).closest('tr');
$.post(url, { id: $(this).data('id') }, function(response) {
if(response) {
row.remove();
}
}).fail(function (response) {
// display error message?
});
});
and modify the controller to
[HttpPost]
public JsonResult DeleteAdvertisementDetails(int id)
{
new AdvertisementManager().DeleteAdvertisementDetails(id);
return Json(true);
}

Related

How to load a PartialView with a button click in ASP.NET MVC

I have a page that basically has two side-by-side divs. In the left div I will have an HTML table with several rows, and in each of those rows, I was trying to place a button that would Render Partial to the right div.
What I've tried below doesn't seem to be working correctly, when I click on the button, nothing is rendered to the right div and if I put a break in debug on the partial view it returns the view for every single row. How do I render the partial view on a button click and not have the partial view render automatically?
<div class="float-container">
<div class="float-childsmall">
#foreach (var watchList in Model.ViewExecutingTradesUserWatchListFollowShort)
{
<table id="customers">
<caption class="text-center"><h2>#watchList.WatchListName</h2></caption>
<caption class="text-center"><p style="font:10px;">#watchList.WatchListDescription</p></caption>
<tr>
<th>Ticker</th>
</tr>
#foreach (var ticker in Model.ViewUserWatchListTickerModel.Where(y => y.UserWatchListId == watchList.UserWatchListId).ToList())
{
<tr>
<td><a target="_blank" href="https://finviz.com/quote.ashx?t=#ticker.Ticker">#ticker.Ticker </a></td>
<td>
#{
<button data-url='#Html.Action("_Research", null, new ViewDataDictionary { { "ChartTicker", #ticker.Ticker } });'>
#Html.DisplayFor(modelItem => #ticker.Ticker)
</button>
<!--Html.RenderPartial("_Research", null, new ViewDataDictionary { { "ChartTicker", "META" } });-->
}
</td>
</tr>
}
</table>
}
</div>
<div class="float-child">
#{
Html.RenderPartial("_Research", null, new ViewDataDictionary { { "ChartTicker", "META" } });
}
</div>
</div>
Here is the action
public ActionResult _Research()
{
return PartialView("_Research");
}

I can't make changes to the database when I click the button

First of all, my code is as follows:
Index.cshtml:
#using ToDoListApp.Models
#model List<TodoTable>
<br />
<div class="p-3 mb-2 bg-dark text-white">All Tasks</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Task</th>
<th scope="col">Urgent</th>
<th scope="col">Done</th>
<th scope="col">Transactions</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<th scope="row">#item.Id</th>
<td>#item.Name</td>
<td>#(item.Urgent ? "Yes" : "No")</td>
<td>#(item.Done ? "Yes" : "No")</td>
<td>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
Transactions
</button>
<ul class="dropdown-menu" aria-labelledby="TransactionsMenu">
<li><a class="dropdown-item" href="/Urgent/#item.Id">#(item.Urgent ? "Unurgent" : "Urgent")</a></li>
<li><a class="dropdown-item" href="#">#(item.Done ? "Undone" : "Done")</a></li>
</ul>
</div>
</td>
</tr>
}
</tbody>
</table>
Controller:
[HttpGet]
public ActionResult Urgent(int id)
{
var Task = db.TodoTables.SingleOrDefault(i => i.Id == id);
return View("Index", id);
}
[HttpPost]
public ActionResult Urgent(TodoTable t)
{
var Task = db.TodoTables.SingleOrDefault(i => i.Id == t.Id);
Task.Urgent = !t.Urgent;
db.SaveChanges();
return RedirectToAction("Index");
}
If the image is:
After pressing the Urgent button in the Drop down menu, if it will do the opposite of the Urgent value in the database. So for example if the value is True it will set False. If it is False, it will set True.
I put my codes above. If the problem is, when I access the page, I get the error "This page could not be found".
Why could this be? How can I solve the problem?
You have to pass the id as a query-string parameter:
https://localhost:7234/Urgent?id=6
So you have to change the href attribute to:
href="/Urgent?id=#item.Id"
If instead you want to pass the id as a route parameter:
https://localhost:7234/Urgent/6
Then you should change the [HttpGet] attribute of your action to [HttpGet("{id:int}")]
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-6.0

delete from model don't work correctly

i have a repeating table in razor mvc , my model is an array
#model Models.Event[]
when i delete any row , every thing is ok and i check data in break point...
but view can't render data correctly and always last row is deleted.
in my code, i want to delete row index 2 ... i give it as hard code , in controller and view true data is passed but at the end, in view (display page) , the last row is deleted and the row with index 2 is there again :(
i pass my model from an partial view to the main page.
here is my javascript codes:
<script type="text/javascript">
$(document)
.ready(function () {
$("#EventsTbl")
.on("click", "tbody .btn-delrow",
function () {
var deletedrow = $(this).closest("tr");
var index = 2; // deletedrow.attr("data-ownum");
var data = $("#edit-Event-form").serialize();
deleteEvent(data, index);
});
function deleteEvent(data,index) {
if (confirm("Do you want to delete product: " + index)) {
var postdata = data;
$.post('/Events/DeleteDetailRow', postdata,
function (response) {
$("#EventsTbl tbody").html(response);
});
}
}
});
</script>
and in controller we have :
[HttpPost]
public ActionResult DeleteDetailRow(Event[] model)
{
var list = new List<Event>(model);
list.RemoveAt(2);
return PartialView("AllDetailRows", list.ToArray());
}
"list" has true data after delete, but i don't know where is the problem. at AllDetailRows model has true data too.
here is my partial view code : (AllDetailRows)
#model Models.Event[]
#for (int i = 0; i < Model.Length; i++)
{
<tr data-rownum="#i">
<td class="input">
#Html.EditorFor(model => model[i].EventExp,new {value=Model?[i]?.EventExp})
#Html.ValidationMessageFor(model => model[i].EventExp, "", new { #class = "text-danger" })
</td>
<td>
<button class="btn btn-sm btn-danger btn-delrow" type="button">
<i class="fa fa-remove"></i>
</button>
</td>
</tr>
}
and this is my main view :
#model Models.Event[]
#* This partial view defines form fields that will appear when creating and editing entities *#
<fieldset>
<div>
<table class="table table-bordered table-striped" id="AdverseEventsTbl">
<thead>
<tr>
<th class="text-center or-bold" style="width: 10%">#Html.LabelFor(model => model.First().EventExp)</th>
<th style="width: 5%">
<button class="btn btn-sm btn-success btn-addrow" type="button">
<i class="fa fa-plus-square"></i>
</button>
</th>
</tr>
</thead>
<tbody>
#Html.Partial("AllDetailRows", Model)
</tbody>
</table>
</div>
</fieldset>
any idea?
thanks is advance

create div dynamically on click of a hyperlink in asp.net mvc

1.I want to dynamically generate div containing textbox with unique id on click of button
<input id="<%:rid %>" type="button" value="reply"/>
2.I also want to use jquery ajax mathod to carry the textbox data to ashx file .
Can anyone help me
code
var lineItemCount = 0;
$(document).ready(function () {
$(".commentbox input[type='button']").click(function () {
var id = $(this).attr("id");
alert(id);
var cid = id.substring(5);
var containerid = "container" + cid;
alert(containerid);
//Increase the lineitemcount
lineItemCount++;
//Add a new lineitem to the container, pass the lineItemCount to makesure
getLineItem()
// can generate a unique lineItem with unique Textbox ids
$(containerid).append(getLineItem(lineItemCount));
});
});
//Create a new DIV with Textboxes
function getLineItem(number) {
var div = document.createElement('div');
//Give the div a unique id
div.setAttribute('id', 'lineitem_' + number);
//pass unique values to the getTextbox() function
var t1 = getTextbox('txt_' + number + '_1');
div.appendChild(t1);
return div;
}
//Create a textbox, make sure the id passed to this function is unique...
function getTextbox(id) {
var textbox = document.createElement('input');
textbox.setAttribute('id', id);
textbox.setAttribute('name', id);
return textbox;
}
iteration through model in aspx page
<%var i=1;%>
<%foreach (var commentitem in item.commentsModelList)
{
<table border="0" class="commentbox">
<tr>
<%var rid = "reply" + i;%>
<div id="<%:containerid %>">
<td> <input id="<%:rid %>" type="button" value="reply"/>
</div>
</td>
</tr>
</table>
<% i++;}%>
I changed your markup little bit to get the corresponding id of items on my click events
HTML
<table border="0" class="commentbox">
<tr>
<td>Some Item text
</td>
</tr>
<tr>
<td>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
</table>
And the Script
$(function(){
$(".commentbox .btnReply").click(function(){
$(this).hide();
var id=$(this).attr("id").split("-")[1]
var strDiv="<input type='text' class='txtCmnt' id='txtReply-"+id+"' /> <input type='button' class='btnSave' value='Save' id='btnSave-"+id+"' /> ";
$("#container-"+id).html(strDiv);
});
$(".commentbox").on("click",".btnSave",function(){
var itemId=$(this).attr("id").split("-")[1]
var txt=$(this).parent().find(".txtCmnt").val();
$.post("/echo/json/", {reply: txt, id: itemId},function(data){
alert(data);
//do whatever with the response
})
});
});
Here is the jsfiddle example : http://jsfiddle.net/UGMkq/30/
You need to change the post target url to your relevant page which handles the ajax response.
EDIT : As per the comment about handing Multiple Divs
As long as you have the container div ids unique, it will work, I just changed the markup to include more than one item.
<table border="0" class="commentbox">
<tr>
<td>Some Item text<br/>
<div id="container-1" ></div>
<input type="button" class='btnReply' id="reply-1" value="Reply" />
</td>
</tr>
<tr>
<td>Some Another Content here <br/>
<div id="container-2" ></div>
<input type="button" class='btnReply' id="reply-2" value="Reply" />
</td>
</tr>
</table>
Here is the sample :http://jsfiddle.net/UGMkq/44/
For the above output to be rendered, you probably want to write your razor syntax like this
<table border="0" class="commentbox">
#foreach (var commentitem in item.commentsModelList)
{
<tr>
<td>Some Another Content here<br/>
<div id="container-#(commentitem.Id)" ></div>
<input type="button" class='btnReply' id="reply-#(commentitem.Id)" value="Reply" />
</td>
</tr>
}
</table>
Instead of creating a new table for each item, I created a new row in existing table.

How to update different targets with MVC Ajax helper?

i'm having a hard time dealing with MVC Ajax helper and trying to refresh certain part of the page. In my code, I have a situation like this:
<div id="ajaxLoadedContent">
<table>
<tr>
<th>
<%: Html.Label("ProductId") %>
</th>
<th>
<%: Html.Label("ProductName") %>
</th>
<th>
</th>
</tr>
<% foreach (var product in Model.Products)
{
%>
<tr>
<td>
<%: direccion.ProductId %>
</td>
<td>
<%: direccion.ProductName %>
</td>
<td>
<% using (Ajax.BeginForm("EditProduct", "MyController",
new { ContainerDiv = "ShowEditProducts" },
new AjaxOptions() { UpdateTargetId = "ShowEditProducts", OnSuccess = "updatePlaceholder" }))
{%>
<%: Html.Hidden("ProductId", product.ProductId)%>
<input type="submit" value="Edit" />
<%} %>
</td>
</tr>
<% } %>
</table>
<script type="text/javascript">
function updatePlaceholder(context) {
var html = context.get_data();
var placeholder = context.get_updateTarget();
$(placeholder).html(html);
return false;
}
</script>
<div id="ShowEditProducts"></div>
</div>
Now, when I press the Edit button, then the 'Editor View' appears, but the problem is that when i Submit that form, then there are two options:
The data is OK, the changes are made, the form dissapears and the list is refreshed.
The data is NOT OK, the forms stays and the validation messages appear.
The problem is that the UpdateTargetId are different for each option.
Option 1 refreshes "ShowEditProducts", while Option 2 refreshes "ajaxLoadedContent". Also, ehe 'Edit View' contains JavaScript that is executed when the view is loaded using the "Edit" button but is not executed when the form contains errors and is re-rendered.
The code of the EditView looks like this:
<% using (Ajax.BeginForm("SubmitEdit", new AjaxOptions() { UpdateTargetId = Model.ContainerDiv}))
{%>
<script type="text/javascript">
// My JavaScript
</script>
<table>
<tr>
<td>
<%: Html.Label("Id")%></br>
<%: Html.TextBoxFor(x => x.Product.ProductId)%></br>
</td>
<td>
<%: Html.Label("Name")%></br>
<%: Html.TextBoxFor(x => x.Product.ProductName)%><
</td>
</tr>
</table>
<input type="submit" value="Save" />
<%: Ajax.ActionLink("Cancel", "EmptyView","Shared", new AjaxOptions() { UpdateTargetId = Model.ContainerDiv})%>
<% } %>
So, now my two big problems are:
1. The JavaScript of the 'Edit View' don't get executed when the the view is re-renderd.
2. How can i update one target is there are errors and another one when there are not.
Thanks
The object being replaced is being set on this line:
var placeholder = context.get_updateTarget();
So instead, you should add a condition here. Eg, instead of returning HTML directly, if you return an object that looks like this:
public class Result
{
public bool Success { get; set; }
public string Html { get; set; }
}
Then you could do something like this:
var result = response.get_response().get_object();
if (result.Success)
$("#ShowEditProducts").html(html);
else
$("#ajaxLoadedContent").html(html);
Alternatively, instead of returning a Success boolean, you could have a property for the ID of the control to replace. This would be more reusable, and might make sense if you want the decision of which control to replace to be done server-side.

Resources