How to show partial view with parameter on click - asp.net-mvc

I have a database with people and phones and i created a partial view that shows persons phones. I want this patial view to be loaded on click at some button like ShowPhones or something like that.
This is how i call view
#Html.Partial("ShowPersonsPhones", item.phones)
This is my partial view
#model IEnumerable<Project.Models.Phone>
<h2>Parial View</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Numer)
</th>
<th>
#Html.DisplayNameFor(model => model.Model)
</th>
</tr>
#foreach (var phone in Model)
{
<tr>
<td>
#Html.DisplayFor(item => phone.Numer)
</td>
<td>
#Html.DisplayFor(item => phone.Model)
</td>
</tr>
}
</table>
EDIT:
i tried to do some javascript in view but it just doesnt work
<style>
.shown{
display : inline;
}
.hidden{
display : none;
}
</style>
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function show_partial(i) {
alert("show partial " + i);
var divsname = '#partial' + i;
div = $(divsname);
if (div.hasClass('hidden'))
{
div.removeClass("shown");
div.addClass("hidden");
}
else
{
div.removeClass('hidden');
div.addClass("shown");
}
}
</script>
When i put alert in the function it shows but doesnt change classes for some reason.

In button click event, you can load the partial view.
ViewPage
<input type="button" id="btn" value="ClickMe" onclick="loadPartialView()" />
<div id="partialDiv"></div>
<script type="text/javascript">
function loadPartialView() {
$("#partialDiv").load('#Url.Action("IndexView","Home")');
}
</script>
In Controller, you can return the partial view with the parameter.
public ActionResult IndexView()
{
return PartialView("_PartialView", db.Phones.ToList());
}

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");
}

Add table controls for asp.net mvc web application using signalR

I want to add controls to sort a table which is rendered in a partial view. The partial view is called using a signalR method. Every time the server updates the database with new information it calls the javascript method to return a new partial view to <div id="customersTable">.
I need a way to pass a query to the controller, and make the last query sent persistent so that when signalR calls the controller action again, the clients actions are remembered.
In addition to sorting I would also like to implement child rows that are expandable via a toggle button in an additional column. I'm not sure how feasible that is using partial views and signalR in this way.
I have partially solved this by adding JQuery controls to the main page. However when AJAX updates the DOM, the controls are reset to their default state, which is something I ultimately want to avoid happening.
Here is the partial view:
#model IEnumerable<XXXX.Models.CustomerModel>
<table class="table table-hover">
<tbody>
<tr>
<th class="col-sm-2">
Name
</th>
<th class="col-sm-2">
SO Number
</th>
<th class="col-sm-2">
Report Time
</th>
<th class="col-sm-2">
Report Date
</th>
<th align="center" class="col-sm-1">
System Status
</th>
</tr>
#foreach (var item in Model)
{
<tr onclick="location.href = '#(Url.Action("SystemDetails", "Monitoring", new { id = item.ID }))'" #(item.Errors == 0 ? String.Empty : "class=danger")>
<td class="col-sm-2">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="col-sm-2">
#Html.DisplayFor(modelItem => item.SONumber)
</td>
<td class="col-sm-2">
#Html.DisplayFor(modelItem => item.ReportTime)
</td>
<td class="col-sm-2">
#Html.DisplayFor(modelItem => item.ReportDate)
</td>
<td align="center" class="col-sm-1">
#if (item.Errors == 0)
{
<i class="glyphicon glyphicon-ok"></i>
}
else if (item.Errors > 0)
{
<i class="glyphicon glyphicon-warning-sign"></i>
}
</td>
</tr>
}
</tbody>
</table>
Here is the javascript method client side:
function getAllCustomers()
{
var tbl = $('#customersTable');
$.ajax({
url: '/Monitoring/GetCustomers',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
And the controller method where the db context is sorted:
public ActionResult GetCustomers()
{
return PartialView("~/Views/Monitoring/_CustomersList.cshtml", db.Customers.OrderBy(c => c.SONumber).ToList());
}

jquery post to asp.net mvc controller

I have these two controller actions:
public ActionResult Index(string search, int? page)
{
return View(db.powners.Where(x => x.petowner.StartsWith(search) || search == null).OrderBy(x => x.petowner).ToList().ToPagedList(page ?? 1, 5));
}
public ActionResult Ownerfind(string search, int? page)
{
return View(db.powners.Where(x => x.petowner.StartsWith(search) || search == null).OrderBy(x => x.petowner).ToList().ToPagedList(page ?? 1, 5));
}
And this json method also:
public JsonResult Getowner(int nownerid)
{
OwnerEntities owner = new OwnerEntities();
var existingCust = owner.powners.Single(p => p.ownerid == nownerid);
return Json(existingCust);
}
Index view:
#model PagedList.IPagedList<Mvc4test2.Models.powner>
#using PagedList.Mvc;
#using PagedList;
#{
ViewBag.Title = "Index";
}
<link href="../../Content/PagedList.css" rel="stylesheet" type="text/css" />
<div style="font-family:Arial">
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
#using (#Html.BeginForm("Index", "owner", FormMethod.Get))
{
<b>Search</b>#Html.TextBox("search")<input type="submit" value="search" />
}
</p>
<table id="ownertable">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().petowner)
</th>
<th>
#Html.DisplayNameFor(model => model.First().ostreet)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ownerid)
</td>
<td>
#Html.DisplayFor(modelItem => item.petowner)
</td>
<td>
#Html.DisplayFor(modelItem => item.ostreet)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ownerid }) |
#Html.ActionLink("Details", "Details", new { id=item.ownerid }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ownerid })
</td>
</tr>
}
</table>
#Html.PagedListPager(Model, page=>Url.Action("Index", new{page, search=Request.QueryString["search"]}), new PagedListRenderOptions(){Display=PagedListDisplayMode.IfNeeded, DisplayPageCountAndCurrentLocation=true,MaximumPageNumbersToDisplay=5})
Ownerfind view:
#model PagedList.IPagedList<Mvc4test2.Models.powner>
#using PagedList.Mvc;
#using PagedList;
#{
ViewBag.Title = "Index";
}
<link href="../../Content/PagedList.css" rel="stylesheet" type="text/css" />
<div style="font-family:Arial">
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<p>
#using (#Html.BeginForm("ownerfind", "owner", FormMethod.Get))
{
<b>Search</b>#Html.TextBox("search")<input type="submit" value="search" />
}
</p>
<p>
hello
</p>
<table id="ownertable">
<tr>
<th>
#Html.DisplayNameFor(model => model.First().petowner)
</th>
<th>
#Html.DisplayNameFor(model => model.First().ostreet)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ownerid)
</td>
<td>
#Html.DisplayFor(modelItem => item.petowner)
</td>
<td>
#Html.DisplayFor(modelItem => item.ostreet)
</td>
</tr>
}
</table>
#Html.PagedListPager(Model, page=>Url.Action("ownerfind","owner", new{page, search=Request.QueryString["search"]}), new PagedListRenderOptions(){Display=PagedListDisplayMode.IfNeeded, DisplayPageCountAndCurrentLocation=true,MaximumPageNumbersToDisplay=5})
</div>
Jquery segment:
$("#ownertable td:nth-child(1)").click(function (event) {
event.preventDefault();
var $td = $(this).closest('tr').children('td');
var currentid = $.trim($td.eq(0).text());
alert("hi:" + currentid);
$.ajax({
url: 'owner/Getowner',
type: 'POST',
data: 'nownerid=' + currentid,
dataType: "json",
success: function (result) {
alert("hello");
//alert(result.petowner);
opener.$('input#ownerid').val(result.ownerid);
opener.$('#petowner').val(result.petowner);
opener.$('input#ostreet').val(result.ostreet);
self.close();
}
});
});
Here's the problem:
If I use the first controller action public ActionResult Index(string search, int? page), then I get the json result as expected. However if I use the second controller action
public ActionResult Ownerfind(string search, int? page) then the I donot get a json result back.
Both controller actions work on screen, and I get the alert("hi:" + currentid);
But I only get a json result if I use click on the table used in the Index view.
Why isn't the ownerfind view working with jquery? It displays correctly just no json result.
I want seperate view, because one will be a lookup and another a regular for adding and editing.
Add [HttpPost] attribute to Getowner action from Contoller
And return from get owner something like this:
return Json(new { Data = existingCust });

retrieving data from database using id and displaying it in view in mvc

My problem is in view...Please give me new view which suits my database and action.
My details table:
Passing request id using html action link:
#Html.ActionLink(item.Request_ID, "Details",new { requestid = item.Request_ID },null )
clicking on the link we should get details corresponding to the link from database.
Action method:
public ActionResult Details(string requestid)
{
var entities = new EmployDBEntities1();
var detailsModel = entities.Details.Single(e => e.Id == requestid);
return View(detailsModel);
//return View(entities.Details.ToList());
}
Hope my problem is returning view and designing view. My requirement is I want details for particular id and should display them in the below designed view. I am able to check the ids in var details model and then I have to read remaining fields from databse and disply the fields in my view.I am notable to do it. Please help me.
View:
model IEnumerable<Approvals.Models.Detail>
#{
ViewBag.Title = "Details";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Header {
#Html.ActionLink("Back", "PendingRequests", "Account", null, new { data_icon = "arrow-l", data_rel = "back" })
<h1>#ViewBag.Title</h1>
#Html.ActionLink("Log Off", "LogOff")
}
<head>
<link href="~/StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>
<div data-role="collapsible" data-theme="b" data-content-theme="b">
<h3>Employee Details</h3>
<table class="td3">
#foreach (var item in Model) {
<tr>
<td>Employee ID</td>
<td>#Html.Encode(item.EmpID)</td>
</tr>
<tr>
<td>Short ID</td>
<td>
#Html.Encode(item.ShortID)
</td>
</tr>
<tr>
<td>Grade</td>
<td>#Html.Encode(item.Grade)</td>
</tr>
<tr>
<td>Vertical</td>
<td>#Html.Encode(item.Vertical)</td>
</tr>
<tr>
<td>Vertical Head</td>
<td>#Html.Encode(item.VerticalHead)</td>
</tr>
<tr>
<td>L1 Manager</td>
<td>#Html.Encode(item.L1_Manager)</td>
</tr>
<tr>
<td>L2 Manager</td>
<td>#Html.Encode(item.L2_Mnager)</td>
</tr>
<tr>
<td>CostCentre</td>
<td>#Html.Encode(item.CostCentre)</td>
</tr>
}
</table>
</div>
model Approvals.Models.Detail
#{
ViewBag.Title = "Details";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Header {
#Html.ActionLink("Back", "PendingRequests", "Account", null, new { data_icon = "arrow-l", data_rel = "back" })
<h1>#ViewBag.Title</h1>
#Html.ActionLink("Log Off", "LogOff")
}
<head>
<link href="~/StyleSheet1.css" rel="stylesheet" type="text/css" />
</head>
<div data-role="collapsible" data-theme="b" data-content-theme="b">
<h3>Employee Details</h3>
<table class="td3">
<tr>
<td>Employee ID</td>
<td>#Html.Encode(Model.EmpID)</td>
</tr>
<tr>
<td>Short ID</td>
<td>
#Html.Encode(Model.ShortID)
</td>
</tr>
<tr>
<td>Grade</td>
<td>#Html.Encode(Model.Grade)</td>
</tr>
<tr>
<td>Vertical</td>
<td>#Html.Encode(Model.Vertical)</td>
</tr>
<tr>
<td>Vertical Head</td>
<td>#Html.Encode(Model.VerticalHead)</td>
</tr>
<tr>
<td>L1 Manager</td>
<td>#Html.Encode(Model.L1_Manager)</td>
</tr>
<tr>
<td>L2 Manager</td>
<td>#Html.Encode(Model.L2_Mnager)</td>
</tr>
<tr>
<td>CostCentre</td>
<td>#Html.Encode(Model.CostCentre)</td>
</tr>
</table>
</div>
Instead of var type for detailsModel object give type what is bound to view i.e. IEnumerable of Approvals.Models.Detail in "Details" action.
your view name should match action name if not supplied in return View(). else return View("xxx", detailsModel ) in "Details" action.

Invalid length for a Base-64 char array or string. when I trying to pass byte[]

I am trying send Byte[] by converting to string from View to controller in #Html.ActionLink. Evey time when I click on ActionLink it is throwing exception. I am attaching code here.
Exception
URL After Action Click
http://localhost:55253/Member/Create?customerContactNumber=0439349
&committeeId=AAAAAAAADLc%3D
View Code
#using VolunteerPoints.BootstrapSupport
#model Tuple<VolunteerPoints.Models.Contact, IEnumerable<VolunteerPoints.Data.Committee>>
#{
ViewBag.Title = "SearchResults";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Activity Search Results</h2>
<table id="Activitieslist" class="table table-striped table-bordered table-hover .table-condensed">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Item2.GetEnumerator().Current.Committee_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Item2.GetEnumerator().Current.Committee_Type)
</th>
<th></th>
</tr>
</thead>
#foreach (var model in Model.Item2)
{
<tr>
<td>
#Html.DisplayFor(modelItem => model.Committee_Name)
</td>
<td>
#Html.DisplayFor(modelItem => model.Committee_Type)
</td>
<td>
<div>
<div>
#Html.ActionLink("Select", "Create","Member", new
{customerContactNumber = Model.Item1.Number, committeeId =
Convert.ToBase64String(model.Committee_Id) }, new { #class = "btn btn-primary" })
</div>
</div>
</td>
</tr>
}
</table>
#section Scripts {
#Styles.Render("~/Content/DataTables/css")
#Scripts.Render("~/bundles/DataTables")
<script type="text/JavaScript">
$(document).ready(function () {
$('#Activitieslist').dataTable({
"bSort": true,
"bPaginate": false,
"bAutoWidth": false,
});
});
</script>
}
Well this part of the URL:
AAAAAAAADLc%3D
should be decoded to
AAAAAAAADLc=
... at which point the length is a multiple of 4, with perfectly reasonable padding at the end.
So I suspect the problem is how/whether the decoding is performed.
(As a side note: byte[] is a pretty unusual representation for an ID. Do you really need it to be done that way?)
Try changing the section of code:
committeeId = Convert.ToBase64String(model.Committee_Id)
To
committeeId = HttpServerUtility.UrlTokenEncode(model.Committee_Id)
This will provide a more URL friendly encrypted string which will avoid characters in the URL that may cause errors.
Hope this helps you James123;

Resources