render partial view in MVC - asp.net-mvc

I am using MVC Structure. I have to create a report which can be filtered by drop downs. I am thing to use a partial view to display report.
HEre is the structure of the page I want to achieve.
On top of page, there will be some drop down lists.
Below these will be page for report.
when user changes the options from dropdownlist, the report will be filtered.
I have two questions
1. How to render partial page.
2. How to refresh partial page through ajax/jquery. I want to do this on client side.
I have checked online, I am rendering page as shown in code below
VIEW
<h3>Report</h3>
<div>
<table>
<tr>
<td>ServiceLine</td>
<td>#Html.DropDownList("ServiceLine", null, new {id="ServiceLine"}) </td>
</tr>
</table>
</div>
<div>
<h2>List</h2>
<div>
#Html.Partial("PartialView")
</div>
</div>
This is what I have got in controller
public ActionResult PortfolioReport(char serviceLine)
{
//Department List
var serviceLines = Enum.GetValues(typeof(SogetiDepartments)).Cast<SogetiDepartments>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((char)v).ToString(),
});
foreach (SelectListItem item in serviceLines)
{
if (Convert.ToChar(item.Value) == serviceLine)
item.Selected = true;
}
ViewBag.ServiceLine = serviceLines;
return View();
}
Any kind of help is appreciated.

You have to use jQuery to achieve this feature
First apply some identifier to your data container
<div id="reportContent">
#Html.Partial("PartialView")
</div>
And then write script on your dropdown change event using jQuery
<script type="text/javascript">
$(function(){
$("#ServiceLine").change(function{
// get data from server using ajax
var url = 'YourPartialPageURL?'+serviceLine+="="+$(this).val();
$('#reportContent').load(url);
});
});
</script>
Note: You should use return PartialView(); from your controller action
And don't use #Html.Partial and use #Html.Action instead.
#Html.Partial loads View directly without going to Controller Action.
It should be used if you have data to be passed with you or if you just want to load some static content on the page

Related

Partial Views, redirected to another URL?

Am trying to build a project using MVC 4 and Razor. Am having trouble understand partial views. I have a list of my domain objects that I iterate through and display it in a list box (each row being clickable). I split this into main view and a partial view which renders the domain object which works fine. Inside my partial view I want to make each item clickable and upon click, I want to create a new partial view displaying details about the domain object.
Here is what I have
My main view looks like this
<div class="panely">
<div class="list-group">
#{ Html.RenderPartial("DomainObjectsPartial");}
</div>
</div>
My partial view looks like this
<div class="list">
#foreach (var x in #Model)
{
<a href="#Html.Partial("DomainObjectPartial")" class="list-item">
<em>#x.Name</em>
</a>
}
</div>
I have a view named DomainObjectPartial, which has nothing but a small div with hello.
When the user clicks on a domain object, I expect the partial view to be rendered within the main view, but instead I get a error saying
A potentially dangerous Request.Path value was detected from the
client (<).
And when I look at my URL, the contents of the partial view are contained within it like
http://localhost/<div>hello</div>
I dont want to be redirected to another URL. I just want the partial view to be displayed below the list. Can anyone explain to me what am i missing or not understanding?
I guess you wanted to use AJAX:
<div class="list">
#foreach (var x in Model)
{
<a href="#Url.Action("Index", "Items", new { id = x.Id })" class="ajax-link">
<em>#x.Name</em>
</a>
}
</div>
and then you will obviously have a controller action which will render this partial:
public class ItemsController: Controller
{
public ActionResult Index(string id)
{
// go get the specific item from your database using the id and pass it to
// the partial view
var viewModel = ...
return Partialview("DomainObjectPartial", viewModel);
}
}
and the last part is to AJAXify this anchor:
$(function() {
$('.ajax-link').on('click', function() {
// Send an AJAX call to the server endpoint pointed by the href attribute
// of the anchor and inject the results of this endpoint execution inside a
// DOM element with id="result"
$('#result').load(this.href);
// By returning false you are canceling the default action of the
// anchor click and prevent the browser to redirect to the url pointed
// by the href property. This would leave enough time for your AJAX request
// to execute and return the results.
return false;
});
});
and you will obviously need a DOM element with id="result" somewhere on your page to harbor the results of the AJAX call:
<div id="result"></div>

Cookieless rendering of a side bar with links enabled based on a parameter

I have an MVC 4 site that renders a left sidebar with a bunch of menu links on it. When the user signs in, they are directed to a page where they search for someone. Once they've selected someone and submitted the form, an id cookie gets set.
This id determines whether or not various links in the sidebar menu are enabled, as it is a required parameter for many of the actions that those links lead to. The menu itself, since it is on every page of the site, is set up in the _Layout partial:
<div id="contentwrapper">
<div id="left-menu">
#Html.Action("Display", "Menu", new { Area = "" })
</div>
<div id="mainbody">
<section>
#RenderBody()
</section>
</div>
<div id="footer">
</div>
</div>
Display returns a partial view representing the sidebar menu. Since I'm rendering the menu sidebar in the _Layout, I don't have a model to work with. Is there any way I can get the parameter to my menu partial view without using a cookie?
I would use a hidden field and viewbag
Public ActionResult Index(){
ViewBag.id = // set your id initially
}
if javascript/jquery is ok with you...
$(function(){
var myID = #Html.Raw(Json.Encode(ViewBag.id));
$('#hidID').val(myID);
});
HTML
<input type="hidden" name="hidID" id="hidID" />
Then.. Display Action
Public ActionResult Display(int hidID){
// this will be current id,
// if id is reset , pass the new one to viewbag , jquery will reset hidden field on client
}

How to load records in MVC-view on demand

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.
currently, data get loaded as soon as that view get called, which I want to avoid it.
I wan to load the data only when user click on the Button, which is on that view.
This is a code of the button.
<input type="button" value="Show" id="ShowId" onclick="LoadData()"/>
And
below Code should be executed when user click on the button.
#foreach (var item in Model)
{
<div id="OwnerName">
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
</div>
<p class="CommentP">
#Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
}
How to do this ?
Here are concrete examples of loading data on demand:
JQuery AJAX with ASP.NET MVC
Load partial page in jquery and ASP.Net MVC
Follow their logic and adapt to your case.
Update
Ajax will do the work either (look into comments). Thanks webdeveloper
Hope this helps
You want to load comments from server after user click the button? The simplest way is use Jquery. Create action which will return PartialViewResult and then make ajax request with jquery.

Best way to display a search form and its results in the same page?

Suppose I have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it.
Right now I'm doing the following but it's not working out exactly the way I want:
"Index" View of my SearchController
#using (Html.BeginForm("SearchResults", "Search", FormMethod.Post, new { #class = "searchform" }))`{
<fieldset>
<legend>Name</legend>
<div class="editor-label">
#Html.Label("Search")
</div>
<div class="editor-field">
#Html.TextBox("Name")
</div>
<input type="submit" value="Search" class="formbutton" />
</fieldset>
#{ Html.RenderPartial("SearchResults", null);
This is my "SearchResults" View:
#model IEnumerable<MyProject.Models.spSearchName_Result>
<table>
#foreach (var item in Model)
{
<tr>
<td>
#item.Name
</td>
</tr>
}
</table>
This is my Controller:
// GET: /Search/SearchResult
[HttpPost]
public ActionResult SearchResult(FormCollection collection)
{
var result = myentity.spSearchName(collection["Name"]);
return PartialView("SearchResults", result);
}
I can only seem to get the results to display on an entirely new page (not being embedded as a partial view), or I get an error when I load the search page because there are no results (since I hadn't searched yet).
Is there any better way to achieve what I'm trying to do? I feel like I'm going against some of the best practices in MVC.
You could return the results in a ViewData object then only show on the view it if is not null.
Very similar to this question MVC 3 form post and persisting model data
For this instance it looks like you are not passing the results to your partial view. Try this?
#{ Html.RenderPartial("SearchResults", Model.Results);
Since you are not persisting your search information using a model, the search information will be lost when the search form is posted.
Given your design and stated goal, it would be best to convert the form in your Index view into an Ajax form, then your controller can send your partial view back to populate a div below your Ajax form.
counsellorben

Can't get RedirectToaction to show completely new page using Ajax.BeginForm in MVC

Hoping someone can help me solve this issue.
I'm using Ajax.BeginForm quite often when I need to update a part of my actual webpage. But if I have a second button in the web form where I need go to a complete different page, and for example do a search and get some values that I need to complete the form. The page turns up in the update panel (updateTargetID) instead of in a complete new View. That is happening even id a do a RedirectToAction in the controller. Of course the ajax.beginform does what I accept it to do, in other words update the panel that shall be updated. But is there a way to get ajax.Beginform to use redirectToaction without updating when the user is choosing to do for example a search instead of sending the form?
I'm working with asp.net MVC,
Problem;
<% using (Ajax.BeginForm(new AjaxOptions() { LoadingElementId = "loadingElement", UpdateTargetId = "SearchResult", InsertionMode = InsertionMode.Replace}))
{%>
<% Html.RenderPartial("Searchfields", Model); %>
<div>
<%:Html.ActionLink("blank", "Index")%>
</div>
<div id="loadingElement" style="display: none">
Load data...
</div>
<div id="SearchResult">
<% if (Model.SearchResult != null)
{
Html.RenderPartial("SearchResult", Model.SearchResult);
} %>
</div>
<% } %>
In the controller (post) I do this among other stuff;
if (Request.IsAjaxRequest())
{
return PartialView("SearchResult", data.SearchResult);
}
But before this I need to do:
if (data.SearchResult.Count() == 1)
{
return RedirectToAction("Edit", "Person", new { Id = data.SearchResult.First).Id});
}
but ofcourse if I do that the hole page i rendered in the corresponding updateTargetId,
I need to render a new view instead. So how can I for exampel use javascript to redirect oncomplete and have the values from the model sent to the script to for exampel do a window.location.replace?
I'm struggling with javascript, so please help me!

Resources