How to load records in MVC-view on demand - asp.net-mvc

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.

Related

Can an Html.Actionlink pass the selected value of a dropdownlist?

I have an MVC razor page where I have two HTML action links which work fine separately, but not together. Before looking into a jQuery option, I wanted to make sure I wasn't missing something obvious. I was hoping I could keep things simple by adding a second parameter to the relevant html.actionlink.
I am making the transition from Web Pages to MVC, so I gathered what I have so far by looking at examples on the Microsoft ASP.NET learning resources and other SO posts.
These are the current (relevant) sections of my cshtml page.
First action (filter by dropdown): At the top of the page I have a dropdown by which I can filter the form by one column value. By itself, it works great.
#using (Html.BeginForm())
{
<p>
Filter by Campus: #Html.DropDownList("searchByFilter", new SelectList(ViewBag.names))
<input type="submit" value="Filter" />
</p>
}
Second Action (sort by column): In the header row of the table, I have an action link, where when a user clicks the column header, the controller serves the table sorted appropriately. I'm just showing a single column out of the table to show you how it works.
<th>
#Html.ActionLink("Campus", "Index", new { orderBy = ViewBag.CampusSortParm })
</th>
The problem: While these work great independently -- for obvious reasons, the two action links don't work together. I was hoping I could keep things simple and do something like this, adding a second parameter which can read the value of the dropdown (null is not an option).
<th>
#Html.ActionLink("Campus", "Index", new { orderBy = ViewBag.CampusSortParm
#*, searchByFilter = selected value of searchByFilter dropdown, but how do I get it here? *# })
</th>
Can I add a second parameter in this fashion, or do I need to look into a jQuery solution?
Thanks to #Stephen Muecke for confirming that the question I posed needed to be done in jQuery or Javascript.
However, after asking myself why my code was able to work so far, I thought of an obvious change I could make. Rather than sorting by column click, I simply make it part of the form submission.
#using (Html.BeginForm())
{
<div>
<p>
Filter by Campus: #Html.DropDownList("searchBy", new SelectList(ViewBag.names))
</p>
<p>
<strong>Sort by Column: </strong>
#Html.DropDownList("orderBy", new SelectList (ViewBag.SortByColumns))
</p>
<p>
<strong>Sort Direction: </strong>
#Html.DropDownList("orderDir", new SelectList(ViewBag.SortDir))
</p>
<input type="submit" value="Apply" />
</div>
}
This works perfectly now for my needs. The result of my question is achieved.

Post checkbox values using MVC property

Is there any way to pass the checkbox values to the controller on checking from a list of checkbox without using any submit button or any jquery Ajax? I just want to use only asp.net mvc property.
As user1576559 sad in comment:
I want to submit the form when I'll check or uncheck any of the
checkboxs without using any jquery or ajax
Here it is:
#using (Html.BeginForm("Update", "Home"))
{
<p>Checkboxes:</p>
#Html.CheckBox("chk1", new { onchange = "this.form.submit()" }); <br/>
#Html.CheckBox("chk2", new { onchange = "this.form.submit()" }); <br />
#Html.CheckBox("chk3", new { onchange = "this.form.submit()" }); <br />
}
As per my understanding, you need to use #Html.CheckboxFor(m=>m.PropertyName) when you send the page to server then you get the updated checkbox status.

render partial view in 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

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