Navigating to different views in Single Page Application - asp.net-mvc

I'm developing Single page web application for which I will be using the MVC and knockout. In the _Layout.cshtml, I will have the menu bar using which user can view different views. When I click on the items in menu, I will be calling controller method and being a single page application, I will have to return partial view. However, I'm confused how I can load returned partial view exactly in my view area. If I use Ajax.BeginForm, I can specify the UpdateTargetID in which I need to update my partial view but as with menu item click, it will just be server method call. So I wonder how I can update the partial view inside view area?
Do you think writing following javascript function for each menu items is what I need to do?
$('#menuitemId').click( function() {
$.ajax({
type: 'POST',
url: '#Url.Content("~/ControllerName/ActionName")',
data: objectToPass,
success: function (data) {
$('#divid').innerHTML = data; // data is partial view returned from controller
}
});
}
Also, can someone point me/share working demo/good documents of Single page web application with MVC and knockout?

That looks fine to me.
You could also make it simpler like this:
$('#menuitemId').click( function() {
$('#divid').load('#Url.Content("~/ControllerName/ActionName")' + menuItemId);
});

Related

MVC 4 load partial view dynamically on single page

I have a MVC 4 application which has a single home view. I have three link buttons and want to load three different forms dynamically based on the button click. I am using mvc partial views. So, if I click on button-1 it should load partialView-1 and should also send value-1 from the corresponding text box to partialView-1.
I am looking for mvc inbuilt approach rather than doing heavy javascript work.
You can do this like this.
A. Have different methods inside your controller returning PartialViewResult
[HttpGet]
public PartialViewResult GetPartialView1(int value)
{
return PartialView("_PartialView1"); //This view should exist in appropriate views folder.
}
B. Your buttons on the left handside should be #Ajax.ActionLink
#Ajax.ActionLink(
"Button1",
"GetPartialView1",
new {
value1 = 1},
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "righthandsidebox"
}
)
C. The UpdateTargetId = "righthandsidebox" that should be the id of the div on the right hand side. Contents of righthandsidebox will be replace by the PartialView
There is nothing built into MVC to do this as what you want to do happens on the front-end. If you want to be dynamic you have to use javascript.
If you want to avoid javascript then it can't be dynamic. You would wrap each button and value in a form and have it submit its value to the back-end and by what is passed you then you have your view render what partial you want. But this wouldn't be dynamic as want it to be.
I'm not sure what you consider as "heavy" when it comes to javscript? With jQuery what you want you do doesn't take much.
(lighter javascript work) You can either have your View place all of the partial views on the page with a class that sets them to display:none then just javascript to simple change out the class to view the partial you would like. But you have a lot of partials then you can do the following.
Or have the buttons make an `ajax call to the back-end fetching the partial that you need.
The bottom line is... if you want dynamic you need to use javascript.

Standard Practice to create PopUp form which then updates parent form dropdown without Parent page refresh?

I am using MVC3, C#, Razor, EF4.1, SQLServer 2008.
I have a parent form with a dropdown for "Suppliers". I wish to add a "quick add" link/button that enables the user to quickly add a supplier to the DB which is then available in the dropdown for selection. At present this is achieved by
Parent Page -> Add Supplier Page -> Parent Page(Page Refresh)
Of course on return to the parent page, it refreshes and removes all non saved data - which is a problem. It would be better to have a popup window which then saves the suppliers and then just refreshes the dropdown portion of the parent page form. So I believe I am seeking an approach to:
Parent Page -> Popup(Modal) -> DB Save -> Refresh DropDown in Parent Page (Ajax???) -> close Modal popup.
I would appreciate guidance on the above, as I am a little stuck on the best practice and hopefully simple approach to this.
Many thanks.
I normally do something like this:
Create an 'Add' button that will display a popup. (I use jQuery dialogs. They are simple, free, and easily to implement by just calling .dialog on a div). Inside this dialog have the appropriate fields needed to create a new supplier. Have a 'Save' button in this dialog and have it wired up to a AJAX post. (Again this is very simple using jQuery)
If you do use jQuery its as simple as submitting that form to your controller action that will then call you data access layer to save the new supplier entity. When the AJAX call comes back successfully you can reload the contents of the supplier grid with another AJAX post. All the 'Magic' comes from implementing AJAX really which will allow for you to retain the users input and not reload the whole page. The AJAX call that is executed after the user enters in a new Supplier and clicks save would look something like this:
In your JavaScript:
$.ajax({
url: "ControllerName/SaveNewSupplier",
Data: $('#YourAddNewSupplierFormName').serialize(),
Type: "POST"
Success: function(result) {
// this is what will get called after a successful save and return of your action method on your controller. This is where you will put the call to repopulate the supplier list with the updated list.
UpdateSupplierList(); // This function is created below
}
});
In your controller:
Public JsonResult SaveNewSupplier (NewSupplierModel newSupplier)
{
// save your new supplier through your data access layer
// if save is successful then return
Return Json({success = true}, JsonRequestBehavior.AllowGet)
}
Then to repopulate the initial div that contains all the suppliers do something like this:
In JavaScript:
function UpdateSupplierList()
{
$.ajax({
url: "ControllerName/GetAllSuppliers",
Type: "GET"
Success: function(result) {
$('#SuppliersDiv').html(result.suppliers)
}
And in your controller:
// remember that a lot of this is pseudo code and your will have to implement it better for your situation. But basically its just:
Public JsonResult GetAllSuppliers()
{
var suppliers = db.GetSuppliers()
return Jason({suppliers = suppliers}, JsonRequestBehavior.AllowGet);
}
EDIT: If you are updating a SelectList via jQuery then this article is almost identical to what I explained but goes into much more detail on updating the select list. Hope this helps.
http://www.joe-stevens.com/2010/02/23/populate-a-select-dropdown-list-using-jquery-and-ajax/

MVC partial render

if renderpartial in MVC is not like Update panel in ASP.net. than how does it works, and what about the efficiency. I heard that update panel was so inefficient in use. But how does MVC handles postbacks, I need to undestand this before I can dive into MVC
Any suggestions
thank you
ASP.MVC Partial views are just reusable HTML fragments that can be populated by View Models. They don't have any special built in functionality like update panels do.
In general terms, with ASP.MVC you control post backs. In fact, you have to code it all yourself in HTML and JavaScript.
I suggest you start here.
Assuming that you want to update part of your page, the method I use is as follows:
Link a JavaScript function to the event you want to use to update the 'panel'
Make a jQuery AJAX call to an action in your controller
from the controller return a call to the partial view
this will cause the resulting HTML from the partial view to be returned as HTML to your AJAX call
use jQuery to add the HTML to an existing empty div
The AJAX call looks something like
$.ajax({
url: yourControllerAction URL,
data: { CodeTypeID: codeTypeID }, // optional data
type: "POST",
success: function (returnedHtml) {
$("#myDiv").html(htmreturnedHtmll);
}
});
The rest is standard MVC
Hope that helps

Is there a clean way to embed a url in a razor view?

I have a partial view in an ASP.NET MVC app:
#Html.Partial("_Comments", Model)
I want to make this partial a "plugin" that can be called from other apps. So, I created a separate action in my controller to return this partial view alone:
public ActionResult Embed()
{
return View("_Comments", new CommentsModel());
}
This action can then be accessed via the URL [root]/Comments/Embed and returns the partial view's HTML.
Is there a clean way to embed the response from this URL in a separate MVC razor view (in an entirely different app)?
Thanks!
Is there a clean way to embed the response from this URL in a separate MVC razor view (in an entirely different app)?
This means client side code, for example:
function getComments() {
$.ajax({ url: '[root]/Comments/Embed',
iframe: true,
success: function (data) {
$("#target-id").html(data);
}
});
}
Edit
In case you use this ajax plugin, if you set
iframe: true
then you access cross domain by iframe transparenlty
I found a solution.
#Html.Raw(new WebClient().DownloadString("[root]/Comments/Embed"))

ASP MVC + AJAX, trying to Update a div asynchronously

I'm new to Asp MVC, and I'm trying to accomplish a little async update (I'm using MVC3 RC2, with Razor, but I can manage with ASPX solutions too).
I have a Master page, which renders a shopping cart box on every page by calling Html.RenderAction("Cart","Shop"). The Cart action of the ShopController calls the database, etc, and outputs the results. This works.
First problem: if I put an ActionLink in this partial view (like Html.ActionLink("Remove")), then even if I call PartialView() from the Remove action, it renders only the shopping cart, and nothing else (in essence, my page disappears).
Second problem: There is a div called "cartContent" inside this partial view. I want to be able to put a link ANYWHERE (not just on the Master page or in the partial view), which when pressed calls a controller Action, and then updates ONLY the cartContent div based on the results. I've tried Ajax.ActionLink but it does the same as Html.ActionLink, even though I imported the Microsoft.MvcAjax js libs.
Also, if I solve the first problem, I want that to be async as well.
What solution do I use? I've tried setting UpdateTargetID to "cartContent", I've tried wrapping the cartContent into an Ajax.BeginForm, nothing. Do I HAVE to use jQuery (which I know nothing of)? Do I serialize some response to JSON, and update the div manually in Javascript? (I'm not really good at JS, I'm coming from the C# side of things)
You put a link wherever you want:
#Html.ActionLink("remove item", "remove", "somecontroller",
new { id = Model.Id }, new { #class = "remove" })
And then in a separate javascript file:
$(function() {
$('.remove').click(function() {
// when the link is clicked
// perform an ajax request:
$.ajax({
url: this.href,
type: 'delete',
success: function(result) {
// when the AJAX call succeed do something with the result
// for example if the controller action returned a partial
// then you could show this partial in some div
$('#someDivId').html(result);
}
});
// don't forget to cancel the default action by returning false
return false;
});
});
Remark: if the div you are updating contains also the link then you might need to use the .live() function or the click event handler will not work the second time because the DOM will be modified:
$('.remove').live('click', function() {
...
});

Resources