I'm preparing an application I wrote in ASP.Net MVC for some light Ajax-y stuff. Basically, I want users to be able to go to different parts of the page without it reloading.
To do this I want to be able to reload the body of my page.
My site master is broken down into a head body and foot div. I want to be able to use something like $("body").load(whateverlink) to refresh the body, but in my case doing this causes the website to be rendered inside the body.
How can I do this successfully?
EDIT: The page is made up of views, not partialviews. In theory I could go and convert all my pages to partials but I'm looking for a way around that if possible.
Thanks
You can get your controllers to return partial views, using JQuery to do a request and update a div with your page content:
JQuery:
function navigate(url){
$.ajax({
url: "/Home/Index",
cache: false,
success: function(html){
$("#content").html(html);
}
});
}
Controller:
public class HomeController : Controller
{
public void Index()
{
return this.PartialView();
}
}
There is a helpful article on BrightMix which might help. It basically renders a partial to a string, which you could then return as part of a ContentResult.
Related
I am working on a Umbraco 7 project started without MVC implemented. I try to implement a loading without page refresh. I am stuck now because I need some Razor code to get Umbraco information but I need jQuery to refresh without page refresh.
Here my code:
$(function () {
$.ajaxSetup({
cache: false
});
$('#filterButton').click(function(){
$('#content').html(#Html.Partial("~/Views/Partials/Preferences.cshtml"));
})
});
I tried with .load()with .html using #Html.Action,#Html.Partial etc, but nothing works. I know it is really simple to link a controller to an action like this but it will take me to much time now to change everything.
Can you say me if it is possible or not?
Please jquery try
$('#content').load("/Partials/Preferences");
another html helpers try
#{
Html.RenderAction("Preferences","Partials");
}
Syntext For
#Html.RenderAction(Action, Controller, Route)
I have a tabstrip that is dynamically populated with a set of partial views. Each of these partial views is an entry form, and some of them have differing Entity Framework data models behind them.
I would like to POST the model to the server with two arguments (a targeted tab index and the model data) whenever a different tab is selected. (To save the tab data)
My issue is that clicking on the tab links seems to be a 'get' action rather than a 'post' action, and I'm having trouble figuring out how to submit data both comprehensive and isolated enough. (comprehensive being the model and isolated being the model associated with a PARTICULAR partial view) I assume I could use JQuery to find and execute the click method of update buttons on the partial view, but that wouldn't preserve a target index.
Is the best method to find a way to uniquely identify the form itself and subsequently post it? Anyone have a hint for me here?
I am not sure what the best method is. What I do is wrap the code in my partial with
#using (Html.BeginForm("Action", "Controller"))
{
}
and then just having a submit button click event. That posts back just the information from that partial. If you wanted to send multiple partials to the same action then I would use a hidden field that is set when the tabs are clicked and you should be able to pull that index using a Request.Form["FieldName"]. Hopefully that helps.
Edit:
You can also try an ajax call back to the server
$.ajax({
url: "#Url.Action("Action", "Controller")",
type: 'post',
data: {id: 'hiddenfield', data: 'data', etc},
dataType: 'json',
contentType: "application/json",
success: function (result) {
(do something)
}
});
to send the model this way you will need to add those fields to the data row. If there is a lot of data I would recommend stringifying it. You can put this call in the submit button click events.
Use ajax call as mentioned. It does not matter whether the element is on parent or partial page. Once the html is rendered, any element on the DOM can be referenced.
I have a some partial views that generally make use of small model data. I have been using Ajax.BeginForm to with js functions defined in the AjaxOptions to catch the partial postback's success or failure when that part is submitted.
I saw no performance penalty as my data has been light. Currently, I have been working on a piece that returns an HTMLFragment from an SSRS report rendered as format "HTML40" in the controller. The JSON serialization of the html portion is taking a long time and I no longer see it as an option. When I changed the Ajax.BeginForm to Html.BeginForm and rendered the report upfront then the payload is lighter and takes less time to render but now I am stuck. How do I issue refresh commands without loading the partial again? This is why I used Ajax.BeginForm in the first place :( Perhaps there is a better way to load the data than what I am doing. I have started looking into callbacks and somehow getting the report pieces a raw byte[] or string as opposed to using json serialization.
Thanks
You can load a whole partial into a div using .load() jQuery function:
$("#someButton").click(function(){
$("#someDive").load("/url", {type: 'POST'}, function(){
});
});
Now, when you click on #someButton, an AJAX call will be made to /url. The /url can return a PartialView that will be loaded directly into your div:
//controller URL
[HttpPost]
public ActionResult Index(){
return PartialView("MyPartialView");
}
You can pass in models as you'd do to regular view.
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.
Here's the situation (using MVC 2.0):
I'm trying to build a feature to allow a user to preview changes they make to their bio/profile without actually committing their changes first. User fills out a form, clicks a "Preview" button and see what their changes look like. One difficulty is the front-end has a different master-page, so we need to render the whole view, not just a control.
Here's the approach I took:
Asynch post the serialized form to a controller action
Manipulate the model to flesh out the collections, etc. that don't get posted
Return the front-end view, passing it this modified model
Catch the response to the asynch method, wrap it in an iframe and write that to a lightboxed div on the page
Code I'm using... Controller action (the BuildPreview method just alters the model slightly)
[HttpPost]
[Authorize]
public ActionResult PreviewProfile(PersonModel model)
{
return View("Person", PeopleService.BuildPreview(model));;
}
HTML/Jquery stuff:
<script type="text/javascript">
$(document).ready(function () {
$("#previewButton").click(function (e) {
$.post("/PreviewProfile", $("#bioForm").serialize(), function (response) {
$("#previewFrame").html(response);
$("#holdMyPreview").modal({
overlayClose: true,
escClose: true,
autoResize: true,
}, "html");
});
});
});
The modal method is just a basic lightbox-esque thing.
Running into two problems:
EDIT - removed this, I was accidentally pulling a child control
The iframe isn't rendering the html (perhaps because it's not valid b/c it's missing html/body/head tags?). If I just drop the response direcltly into the div, without the iframe, it works... albiet with the wrong stylesheet. If I try to insert it into iframe it just treats it as an empty page, just the html, head and body tags show up.
Any thoughts?
Sam
PS: Tried this over at MSDN forums (http://forums.asp.net/t/1675995.aspx/1?Rendering+a+view+into+a+string+) and it didn't get anywhere, figured I'd see if SO has any brilliance.
so, just massage the response when you get it back, add the missing html/body/head
$.post("/PreviewProfile", $("#bioForm").serialize(), function (response) {
response = "<html><body>"+response+"</body></html>";
$("#previewFrame").html(response);
$("#holdMyPreview").modal({
overlayClose: true,
escClose: true,
autoResize: true,
}, "html");
});