Updating partial view with Jquery in ASP.NET MVC C# - c#

I am using MVC C# along with Jquery.
I have a partial view in a rather large page that has a number of tabs.
On a click of a checkbox, I like to update the partial view WITHIN the form.
What I am getting instead is just the partial view
Here is my code in Jquery:
$('#activelist,#inactivelist').change(function () {
var status = 'inactive';
window.location.href = '#Url.Action("Skits","KitSection")' + '?id=' + id+ '&status=' + status;
});
Any idea on how I could update the partial view within a form in terms of how I would make a call to it?
Here is the code for the PartialView
return PartialView(Kits);
As mentioned, what I see is just the partial view displayed and not the whole form.

window.location.href will reload the entire page. You need to reload some part of your page without a complete reload. We can use jQuery ajax to do this. Let's Find out what jQuery selector you can use to get the Partialview.
For example , Assume your HTML markup is like this in the main form ( view)
<div>
<p>Some content</p>
<div id="myPartialViewContainer">
#Html.Partial("_FeaturedProduct")
</div>
<div>Some other content</div>
</div>
And here the DIV with ID myPartialViewContainer is the Container div which holds the content of the partial view.So we will simply reload the content of that div using jQuery load method
$(function(){
$('#activelist,#inactivelist').change(function () {
var id="someval";
var status = 'inactive';
$("#myPartialViewContainer").load('#Url.Action("Skits","KitSection")' + '?id=' + id+ '&status=' + status)
});
});

You are redirecting the user, via the window.location.href property, to the URL of your partial, hence only displaying that partial.
You should instead do an AJAX call to the partial to retrieve it's HTML and then use something like the .append method to add it to whatever container element you want it to be added to.
EDIT: The .load() jQuery ajax method is actually better for this specific situation.

Related

MVC Render section scripts in controller

I would like to render the "scripts" section of the .cshtml view inside the controller as a string. Is this possible?
What I actually want to do is get the scripts with a separate ajax call and then run eval on the script after loading the html of the view also with ajax.
I've tried looking for related topics but haven't come up with anything relevant. Some related answers fool around with HtmlHelper.ViewContext.HttpContext.Items[""] but I'm unsure how to use it.
What I want is something like this: string scripts = GetScriptsForView(action, controller); which returns the section used in the view like this: #section Scripts {
To clarify (edit):
I'm trying to replace the "RenderBody()" of the layout page with ajax calls, so that I don't have to load the layout containing the static header every time.
I have managed to replace all <a>-tags with ajax calls replacing the <div> containing the view, but am unable to get the javascripts working.
I could remove the #section scripts { from the cshtml-files and let the script tag get loaded with the html view. The problem with this is that if I reload the page it calls the scripts for that view before calling the scripts of the layout page, resulting in errors. Therefore I wish to load the scripts separately.
TL;DR
While you can load sections and contents in separate requests (see example 1), but you don't need to do that. Instead:
You can have different Layout pages for different purposes and dynamically decide which layout to use for the view. For example a full layout page for normal requests and a simple layout page without headers and footers for ajax requests (see example 2).
You can decide dynamically about the layout page in _ViewStart.cstml or in the controller, based on different request parameters, like Request.Headers, Request.QueryString, Request.IsAjaxRequest, etc.
Long Answer
Here are some useful notes about the layout, section, view and partial view which may help you to handle the case:
Specify Layout in return View() - When returning a View you can specify the layout for the view. For example return View("Index", masterName: "_SomeLaypout"). You can have some logic to dynamically decide about the layout name.
Specify Layout in _LayoutStart.cshtml - When returning a View, you can specify the Layout in _ViewStart.cshtml file, for example #{ Layout = "_Layout"; }. You can have some logic to dynamically decide about the layout name.
Render content without Layout - When return a view using PartialView() method, it will render the whole content of the view without any layout or without rendering any section. It's equivalent to using return View and setting Layout to null, in _ViewStart.cshtml)
Render Section without any Content - You can have a layout having just a RenderSection method. Then if you return a view using that layout, it just renders the specified section of that view and will ignore the contents.
Scripts with/without Section - Considering above options, when you put scripts in the script tag without putting in a Section, you guarantee they will be returned as part of the result, regardless of calling return View or return PartialView or having or not having Layout. So in some cases you may want to put scripts without sections. In this case, when you load the partial view using ajax call, it contains the content as well as scripts of the partial view.
In some cases you may want to have some common content/scripts even for partial views, in such cases you can use Section, also have a Layout page which renders the section and contains common things that you want to have in all partial view. In this case you need to return the partial view using return View and specify that specific layout page.
Example 1 - Return just scripts or just content in an ajax request
The following example shows how you can send an ajax request to get content and send an ajax request to get scripts section.
Please note, I don't recommend using different requests for getting
content or getting scripts separately and this example is just for
learning purpose to show you what you can do with Layout pages and
_ViewStart.
To do so, follow these steps:
Change the _ViewStart.cshtml content to:
#{
if(Request.QueryString["Layout"]=="_Body")
{
//Just content of the page, without layout or any section
Layout = null;
}
else if (Request.QueryString["Layout"] == "_Script")
{
//Just script section
Layout = "~/Views/Shared/_Script.cshtml";
}
else
{
//Everything, layout, content, section
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
Note: Instead of a Request.QueryString, you can easily rely on a Request.Header or Request.IsAjaxRequest() or ... base on your requirement.
Then just for _Script, add a new layout page named _script.cshtml having the following content:
#RenderSection("scripts", required: false)
Then:
To get the script section, send a normal ajax request and add the following query string: Layout=_Script.
To get the content without script section, send a normal ajax request and add the following query string: Layout=_Body.
To get the whole content, send a normal ajax request without specifying any Layout query string.
For example, assuming you have a Sample action in Home controller:
[HttpGet]
public ActionResult Sample()
{
return View();
}
Which returns the following Sample.cshtml view:
<div id="div1" style="border:1px solid #000000;">
some content
</div>
#section scripts {
<script>
$(function () {
alert('Hi');
});
</script>
}
In client side, to get the script section:
<button id="button1">Get Sample Content</button>
<script>
$(function () {
$('#button1').click(function () {
$.ajax({
url: '/home/sample',
data: { Layout: '_Script' },
type: 'GET',
cache: false,
success: function (data) { alert(data); },
error: function () { alert('error'); }
});
});
});
<script>
Example 2 - Return Content Without Layout Using Ajax requests
In this example, you can see how easily you can return content and scripts of the views without layout for ajax requests.
To do so, follow these steps:
Change the _ViewStart.cshtml content to:
#{
if(Request.IsAjaxRequest())
{
Layout = "~/Views/Shared/_Partial.cshtml";
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
Add a new layout page named _PartialView.cshtml having the following content:
#RenderBody()
#RenderSection("scripts", required: false)
Get the view using ajax. For example, assuming you have a Sample action in Home controller:
[HttpGet]
public ActionResult Sample()
{
return View();
}
Which returns the following Sample.cshtml view:
<div id="div1" style="border:1px solid #000000;">
some content
</div>
#section scripts {
<script>
$(function () {
alert('Hi');
});
</script>
}
Get the result using ajax:
<button id="button1">Get Sample Content</button>
<script>
$(function () {
$('#button1').click(function () {
$.ajax({
url: '/home/sample',
type: 'GET',
cache: false,
success: function (data) { alert(data); },
error: function () { alert('error'); }
});
});
});
<script>
As per my understanding I guess you are looking for load the page via Ajax without reloading the entire page.
Did you check the Kool Swap Jquery plugin? Hope this will match your requirement.

Refresh view component .net core RC2

I have one normal view with two views components inside. Normal view have also a button and the both views components have a button too.
How i can refresh the views components after clicking on button from normal view?
And how i can refresh second view component after clicking on botton from first view component?
I already tryed to find a way, but without success!
Best regards
Ultimately view components generate HTML markup when razor executes that code. If you want to update some part of your HTML page (like a partial page update), you may consider using jQuery and ajax to do that.
Something like this.
$(function(){
$("#SomeButton").click(function(e){
e.preventDefault();
//make the ajax call and get new data/markup for the
// div rendered by your first view component and update it
var url="TheUrlToActionMethodWhichReturnsPartialMarkup";
$("#DivIdA").load(url);
});
});
You can do the same thing for updating other parts of your page ( markup generated by view component 2) as well. Update the url to an action method which returns a partial view result.
I tried this:
`$("#buttonrefresh").on("click", function () {`
`$.ajax({`
`type: "GET",`
`url: '#Url.Action("VCTest")'`
`(function (result) {`
`$("#show").html(result);`
`});`
`});`
This script is to refresh one view component after clicking on button from normal view.
VCTest is the name of the view component.
show is the name of the div where the view component is called.

How to share information between partial views in JS

Two partials loaded on the same page
For example, if I hit a button in one partial then I want some value to appear in the other partial.
I want all the work to be done on the client side. I am sure I would call a method in js but I am not sure how to connect it to another js var on another partial within the same page. In other words how do I get both the partials to talk to eachother on the client side.
Once your razor view is rendered to the browser, It is just HTML markup. That means, you can use javascript to access the elements in the DOM and update the values as needed.
Keep your script in the main view which holds the 2 partial views.
$(function(){
$("#ButtonInFirstParial").click(function(e){
e.preventDefault();
$("#DivInSecondPartial").html("Updated");
});
});
Also if you declare your javascript variable in a global scope, you can access it in other places also. So if you have a variable like this in your layout page,
<body>
#RenderBody()
<script type="text/javascript">
var global_SiteUrl="Some value i want to access in all pages";
</script>
</body>
You can access it in other views (which uses the above one as the Layout), or js files which are a part of other views who has the layout value set as the above layout.

fire javascript function after partial view is rendered in C# MVC

I have an MVC view that after the client click a button a partial view is rendered.
I want to use: window.scrollTo(0, document.body.scrollHeight); after the partial view is fully rendered, so the client will "jump" to the result of the click.
the thing is: it fires before the partial view is rendered and goes to the bottom of the screen as is before the page height is extanded...
how can I force it to wait untill the partial view is fully rendered?
Thank you!
If you use $().load your can use the callback to do whatever you want when load is done.
$('#___').load('/Home/___?departmentId=' + departmentId, function() {
alert( "Load was performed." );
});
Simply place that
<script type="text/javascript">
function ScrollTobottam() {
window.scrollTo(0, document.body.scrollHeight);
}
</script>
at bottom of partial view then it will load only after partial view is loaded fully

How to update part of a cshtml shared layout on intervals?

I want to modify the content of a div in my shared layout when there is an update at my database. Whats the best way to go about it ? Timers to check database + somehow update view from controller ? In view c# functions ? ajax ?(don't know much about it) or some other way ? Thanks in advance.
Use setTimeout utility of javascript to get timer behavior.
Create a Controller Action and its associated partial view which will have the content you need to load dynamically. You can return a formatted Html from the view or a structured Json object from the controller action whichever is suitable for you..
considering that your following is your DIV tag.
<div id="dynamicContent"></div>
use
$(function(){
var function updatecontent()
{
$("#dynamicContent").load(URL)
setTimeout(updatecontent,5000);
}
setTimeout(updatecontent,5000);
});
to load content dynamically, url would be
YourDomain.com/Controller/Action
$.load()
will load the content of partial view using Ajax, and you will get a nice behavior on page.

Categories

Resources