delete from model don't work correctly - asp.net-mvc

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

Related

MVC Partial Page returns whole page, not just the partial

I have a button on a page:
<div>
From:
<input id="fromDate" type="date" name="fromDate" value="#a.FromDate">
To:
<input id="toDate" type="date" value="#a.ToDate">
<button type="button" id="btn_transactions" class="btn btn-primary" onclick="btnTrans()"><span class="glyphicon glyphicon-search"></span></button>
<label class="buy-heading">Total Buys: #String.Format("{0:n0}", #q.BuyQuantity)</label><label class="sell-heading">Total Sells: #String.Format("{0:n0}", #q.SellQuantity)</label>
</div>
It calls this function on click:
function btnTrans() {
var postdata = { "symbol": $("#savesymbol").val(), "fromDate": $("#fromDate").val(), toDate: $("#toDate").val() };
var url = "Company/Transactions?symbol=" + $("#savesymbol").val() + "&fromDate=" + $("#fromDate").val() + "&toDate=" + $("#toDate").val();
$.ajax({
url: url,
success: function (result) {
alert(result)
$('#transTarget').html(result);
},
error: function () {
//alert("Error occured");
}
});
}
The controller method is:
public async Task<PartialViewResult> Transactions(string symbol, string
fromDate, string toDate)
{
return PartialView("Transactions");
}
This is the partial view:
<table id="transactionsTable" class="table table-bordered display hover no-wrap dataTables" style="width: 100%">
<thead>
<tr>
<th>Account Category</th>
<th>Trade Date</th>
<th>Account Name</th>
<th>Activity</th>
<th>Quantity</th>
<th>Exec Price</th>
<th>Principal</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
var a = item.accounts;
foreach (var item2 in a)
{
<tr>
<td>#item2.AcctCategory</td>
<td>#String.Format("{0:MM/dd/yyyy}", #item2.TradeDate)</td>
<td>#item2.AccountName</td>
<td>#item2.Trans</td>
<td>#String.Format("{0:n}", item2.Quantity)</td>
<td>#String.Format("{0:n}", item2.ExecutionPrice)</td>
<td>#String.Format("{0:n}", item2.PrincipalAmount)</td>
</tr>
}
}
</tbody>
</table>
I have 3 partials on this page as follows:
<div class="mycontent2">
#{Html.RenderAction("Documents", "Company");}
</div>
<div class="mycontent2">
#{Html.RenderAction("Holdings", "Company");}
</div>
<div class="mycontent2">
#{Html.RenderAction("Transactions", "Company");}
</div>
The problem is that the partial view returned from the controller method returns the WHOLE page, not just the partial part of transactions. What am I doing wrong?
Return a model from the controller. Like this;
return PartialView("Transactions", model);
Do it for others partial.
Then, you will use model in your view.
Use #{ Layout = null; } in your partial view.

asp.net mvc razor submit button with code in the cshtml page

I am new to MVC. Not sure how to NOT have the page do a full blinking refresh on click of the submit button. Have not found examples on this other than to put the code in an action in my controller, and I would prefer to have the code as I have it below. Thank you for your assistance!
<form method="post">
<div style="float: left">
Enter the number of days previous to today for which to search: <input type="text" name="NumberOfDays" value="#Request.Form["numberOfDays"]"/>
</div>
<div class="puck-button">
<input type="submit" value="GO!" class="btn btn-primary"/>
</div>
<br/><br/><br/><br/>
#{
var numberOfDays = int.Parse(Request.Form["NumberOfDays"].IsNullOrWhiteSpace() ? "0" : Request.Form["NumberOfDays"]);
var startDate = DateTime.Today.AddDays(-numberOfDays);
<table id="puckBoard" class="gridView">
<thead>
<tr>
#foreach (var item in Model.ProcessSteps)
{
<th>
<div class="puck-step">
#Html.DisplayFor(modelItem => item.Description)
</div>
</th>
}
</tr>
</thead>
<tbody>
#if(startDate != DateTime.Today) { #CompactTableRows(startDate, Model.Modules) }
else
{ #GetSimpleModuleTableRow(Model.Modules) }
</tbody>
</table>
}
</form>

How refresh a view in 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);
}

Partial View with self updating

I'm learning ASP.NET MVC and I've encountered a problem in my practice project (MVC Music Store). I have made a partial view to search for an artist. I expect the partial view to take no arguments and work on its own.
Partial view in the right half part
I have a view specific model for the Artist Search Partial View. The model is as follows:
public class ArtistSearch
{
public string SearchString { get; set; }
public List<Artist> SearchResult { get; set; }
public ArtistSearch()
{
SearchResult=new List<Artist>();
}
}
Controller code is as follows:
public ActionResult Search(string query)
{
ArtistSearch asResult = new ArtistSearch();
if (query != null)
{
var temp = from a in db.Artists
where a.Name.Contains(query)
select a;
asResult.SearchResult = temp.ToList();
asResult.SearchString = query;
}
return PartialView(asResult);
}
The Partial View is as follows:
#model MvcMusicStore.Models.ArtistSearch
<div class="big-search-box">
<form action="#Url.Action("Search","Artist")" method="post" role="form">
<div class="input-group">
#Html.TextBox("query", #Model.SearchString, new { #class = "form-control nrb input-lg", placeholder = "Input your search query..." })
<div class="input-group-btn">
<input type="submit" name="Send" value="Search" class="btn btn-primary btn-iconed btn-lg" />
</div>
</div>
</form>
</div>
<div class="big-search-result-info clearfix">
<div class="pull-left">Showing results for <strong>#Model.SearchString</strong>.</div>
<div class="pull-right"><strong>#Model.SearchResult.Count</strong> artist(s) found.</div>
</div>
<table>
#foreach (var item in #Model.SearchResult)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a href="#item.Id" >
<img src=#item.PhotoURL alt=#item.Name style="width:100px;height:70px;">
</a>
</td>
</tr>
}
</table>
I wish to place this partial view anywhere on the site. Lets say i placed it(using RenderAction) on Artist/Index Controllers View page.
The simple functionality that I'm trying to achieve is that when i click on search it should self update the partial view with search results. Right now it is transferring me to Artist/Search page.
Thanks for the patience.
Try to use Ajax.BeginForm, below is an example:
Action
public ActionResult Search(string query)
{
ArtistSearch asResult = new ArtistSearch();
if (query != null)
{
var temp = from a in db.Artists
where a.Name.Contains(query)
select a;
asResult.SearchResult = temp.ToList();
asResult.SearchString = query;
}
return PartialView("MyParitalView",asResult);
}
View
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("Search", "Home", new AjaxOptions { UpdateTargetId = "result" }))
{
<div class="input-group">
#Html.TextBox("query", #Model.SearchString, new { #class = "form-control nrb input-lg", placeholder = "Input your search query..." })
<div class="input-group-btn">
<input type="submit" name="Send" value="Search" class="btn btn-primary btn-iconed btn-lg" />
</div>
</div>
}
<div id="result"></div>
Parital View : MyParitalView
#model MvcMusicStore.Models.ArtistSearch
<div class="big-search-result-info clearfix">
<div class="pull-left">Showing results for <strong>#Model.SearchString</strong>.</div>
<div class="pull-right"><strong>#Model.SearchResult.Count</strong> artist(s) found.</div>
</div>
<table>
#foreach (var item in #Model.SearchResult)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a href="#item.Id">
<img src=#item.PhotoURL alt=#item.Name style="width:100px;height:70px;">
</a>
</td>
</tr>
}
</table>

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.

Resources