Load partial view depending on dropdown selection in MVC3 - asp.net-mvc-3

Im trying to create a from using asp.net mvc3.
I have a dropdownlist with some options.
What i want is different partial views to be injected into the page, depending on the selection in the dropdown list.
But. i dont want this to rely on a submit action. It should function so that, the partial view is loaded as soon as you select from the select list.
I have this code:
#using (Ajax.BeginForm("Create_AddEntity", new AjaxOptions {
UpdateTargetId = "entity_attributes",
InsertionMode = InsertionMode.Replace
}
))
{
<div class="editor-label">
#Html.Label("Type")
</div>
<div class="editor-field">
#Html.DropDownList("EntityTypeList", (SelectList)ViewData["Types"])
</div>
<div id="entity_attributes"></div>
<p>
<input type="submit" value="Create" />
</p>
}
But I can't figure out how to trigger this partial view load when the dropdown list selection changes.
This point is that the form is different for the different "entity types". so there will be loaded a different partial view, depending on the dropdown selection.
Anyone got any pointers?

Let's say following is your view that you want to insert your partial.
<html>
<head><head>
<body>
<!-- Some stuff here. Dropdown and so on-->
....
<!-- Place where you will insert your partial -->
<div id="partialPlaceHolder" style="display:none;"> </div>
</body>
</html>
On the change event of your dropdownlist, get partial via jquery ajax call and load it to place holder.
/* This is change event for your dropdownlist */
$('#myDropDown').change( function() {
/* Get the selected value of dropdownlist */
var selectedID = $(this).val();
/* Request the partial view with .get request. */
$.get('/Controller/MyAction/' + selectedID , function(data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
And in your controller action which is /Controller/MyActionin above jquery, return your partial view.
//
// GET: /Controller/MyAction/{id}
public ActionResult MyAction(int id)
{
var partialViewModel = new PartialViewModel();
// TODO: Populate the model (viewmodel) here using the id
return PartialView("_MyPartial", partialViewModel );
}

add the following code to the header of the project (layout).
Add "combobox" to any combo box (select box) which you want to trigger the form that is surrounding it.
$(document).ready(function () {
$('.formcombo').change(function () {
/* submit the parent form */
$(this).parents("form").submit();
});
});

Related

Update partial view after edit

I have the following index:
<div id='addProduct'>
#{ Html.RenderPartial("Create", new BoringStore.Models.Product()); }
</div>
<div id='productList'>
#{ Html.RenderPartial("ProductListControl", Model.Products); }
</div>
The partial Create view contains an invisible div which is used to create a new product.
After doing so the partial view ProductListControl is updated.
Now I want to do so with an edit function.
Problem: It's not possible to integrate the edit page while loading the index because at this moment I don't know which product the user wants to edit.
My thought:
I'd like to call my existing edit view in an jquery modal (not the problem) so the user can perform changes.
After saving the modal is closed (still not the problem- I could handle this) and the ProductListControl is updated (here's my problem ... :().
How am I able to do so?
I've seen some tutorials but I'd like to keep it as clean & easy as possible.
Most of them are using dom manipulating and get feedback from the server (controller) by a JsonResult.
If possible I'd like to stick to the razor syntax, no pure JavaScript or jquery and if possible I'd like to avoid JsonResults.
One way might be to use the Ajax.BeginForm for your create product view.
The Ajax.BeginForm accepts a number of AjaxOptions, one being the UpdateTargetId (your DOM id, in this case your productlist div), more info here.
Then in your product controller code you can return a partial view, with the product list. So for example:
Index.cshtml
#using (Ajax.BeginForm("AjaxSave", "Product", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "productList", InsertionMode = InsertionMode.Replace }))
{
// your form
<p>
<input type="submit" value="Save" />
</p>
}
...
<div id="productList">...
</div>
ProductController.cs
[HttpGet]
public ActionResult AjaxSave(Product product)
{
if (ModelState.IsValid)
{
// save products etc..
}
var allProducts = _productService.GetAllProducts();
return PartialView("ProductListControl", allProducts);
}
There is a nice article on about this here.

Reloading main view after button in PartialView is clicked

I have a partial view that the user can preform a search in, and the search results are shown in a select box. In my main view I have a section that is supposed to show the search results after a select button is pressed. Right now when I click the select button is loads the correct information into the correct model for my main view, but the main view doesn't change. When I click refresh, the page updates correctly. How do I make the page update automatically when a button is clicked in the plugin view?
My section in the main view (Index.vbhtml) in my main app:
#Section CUInfo
Credit Union Name: #Model.CUInfo.CUName
end section
Here is my controller method in my Plugin:
Function ChangeCUInfo(strCUName As String) As ActionResult
m_hostApp.CUInfo.CUName = strCUName
m_hostApp.blnPluginRefreshButtonPressed = True
Return View("Index", m_hostApp)
End Function
I've tried to set a boolean value in the hostApp object and then in my main razor view call this function if it is true:
#code
If Model.blnPluginRefreshButtonPressed = True Then
#<script type="text/javascript">
$(function () {
window.location.reload();
});
</script>
End If
Model.blnPluginRefreshButtonPressed = False
End Code
EDIT:
JS function called when the select button is clicked:
function loadCU(CUInfo) {
strCU = CUInfo.split('|');
strCUName = strCU[0];
$.ajax({
type: "POST",
url: "/CUContractNumberPlugin/ChangeCUInfo",
data: { "strCUName": strCUName }
});
}
Form that is used in the plugin view:
#Using (Html.BeginForm("ChangeCUInfo", "CUContractNumberPlugin"))
#<div id="LogoSigSearch" style="height:300px;width:500px;position:relative;">
<span style="display:inline-block;height:20px;width:166px;position:absolute;top:35px;left:5px;">Credit Union Name</span>
<br />
#Html.TextBox("strCUName")
<input type="submit" name="LogoSigSearch$ctl02" value="Search" id="LogoSigSearch_ctl02" tabindex="3" style="width:60px;position:absolute;top:5px;left:352px;" />
<input name="LogoSigSearch$ctl05" type="button" onclick="javascript:clearSearch()" value="Clear" style="position:absolute;top:35px;left:352px;width:60px;" />
<select size="4" name="LogoSigSearch$ctl06" id="LogoSigSearch_ctl06" tabindex="5" style="height:230px;width:342px;position:absolute;top:65px;left:5px;"></select>
<input type="button" name="SelectCU" value="Select" onclick="javascript:loadCU(LogoSigSearch_ctl06.options[LogoSigSearch_ctl06.selectedIndex].value)" tabindex="4" style="width:60px;position:absolute;top:65px;left:352px;" />
</div>
End Using
Are both buttons part of a form? A button won't invoke an action without you attaching it to script or making it part of a form with an associated action.
Use a partial view to render the results of the query, even on the main page load. This simplifies your development.
Add a jQuery event handler (jQuery.on()) to watch for the button click on your main page, or if the button is returned in the partial view, just use an on ready handler in your partial and attach a button.click() event, again using jQuery.
The jQuery event handler can take care of submitting the values of the query, posting to your controller, and displaying the results. I have a number of older articles here but they are still relevant to your question and demonstrate submitting data and fetching partials.
Your client-side code will end up looking something like this:
$("#your-button").click(function () {
var fetchUrl = '#Url.Action("ActionName", "Controller")';
$.post(fetchUrl, { searchParams: $("#your-search-box").val() })
.success(function (data) {
// replace the contents of the DIV with the results. 'data'
// here has whatever you sent back from your partial view
})
.error(function (data) {
// handle the error, use a DIV with some kind of alert message etc
});
});
Hope this helps some.

View with multiple partial views posting back

I'm new to MVC (MVC3) so not sure about the best way to implement this.
I want to create a single "main" view (not strongly-typed). This "main" view will contain multiple strongly-typed partial views that each contain a form. Each partial view will therefore post back to their own POST action that does whatever. The problem I see is that when a partial view posts back, it needs to only update the partial view itself and not affect the other partial views on the page.
When I postback from a partial view now, it just returns the partial view alone back, rather than the entire "main" page.
How can this functionality be achieved in MVC3? (from a high-level perspective)
Thanks
You can post data by AJAX.
In my example I use jQuery:
<div id="first-form" class="form-container">
#Html.Partial("FirstPartial")
</div>
<div id="second-form" class="form-container">
#Html.Partial("SecondPartial")
</div>
// and here go rest forms
Your partial view may be following:
#model YourModelClass
#using (Html.BeginForm())
{
// some fields go there
}
<input type="button" value="Save Form Data" class="save-button"/>
Js would be following:
$("input.save-button").on("click", function () {
var button = $(this);
var container = button.closest("div.form-container");
var url = container.find("form").attr("action");
container.busy($.post(url, function (response) {
container.html(response);
}));
return false;
});

Using Fancybox with ASP.NET MVC Ajax

I have a form which loads within a fancybox so that if the user clicks on a link, a form loads up in fancybox, its an #Ajax.BeginForm(). Like so:
#using (Ajax.BeginForm("AddToBasket", new { controller = "Orders" }, new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SuccessBasket",
OnSuccess = "goToCheckout"
}, new { #class = "product-order-form" }))
{
#* Form elements for Model *#
<div id="SuccessBasket"></div>
}
This gets loaded up in a fancybox window. When I submit the form, my SuccessBasket div does not get updated with the new content passed from the controller, is there some way to enable Ajax calls to be updated within Fancybox? This works fine if I don't use fancybox but I wish to use it.
EDIT:
The form is loaded like so:
#Ajax.ActionLink("Order", "OrderProduct", new { controller = "Orders", id = ViewData["ID"], search = ViewData["search"] }, new AjaxOptions()
{
UpdateTargetId = "ModalWindow",
InsertionMode = InsertionMode.Replace,
OnFailure = "NotAuthorised"
}, new { #class = "lightbox order-link" })
I have an empty div called ModalWindow which is wrapped by a div set to display: none as per the instructions:
<div style="display: none">
<div id="ModalWindow">
</div>
</div>
OrderProduct Action in my controller returns a PartialView:
return PartialView("_OrderProduct", basket);
Where basket is my model BasketModel basket = new BasketModel();
My _OrderProduct PartialView is the view which contains the Ajax form at the start of my post. Which has the SuccessBasket div.
Upto this point, it works perfectly. The form loads up in fancybox.
The AddToBasket Action returns a PartialView:
return PartialView("_BasketSuccess");
This view simply tells the user that their item was added to the basket:
<p>This item has been added to your basket. Search again or goto #Html.ActionLink("checkout", "Order", new { controller = "Orders" }, new { #class = "checkout-link" }) to continue.</p>
The problem is, the SuccessBasket div does not update with the text above but through debugging, I can see that it does load the view _BasketSuccess, it just doesn't update in the modal window.
The way you are loading the fancybox is strange. You are sending 2 AJAX requests: one for the Ajax.ActionLink and one by the fancybox. All that is not necessary. Also you don't need a hidden div in your main view, the fancybox does all this automatically.
So to recap, in your main view all you need is a simple HTML link to the controller actin which will return a partial containing the form:
#Html.ActionLink("Order", "OrderProduct", "Orders", null, new { #class = "lightbox" })
and in a separate javascript file you will attach the fancybox to this anchor so that when it is clicked it will automatically send an AJAX request (the fancybox, not you), fetch the partial form and show it:
$(function () {
$('.lightbox').fancybox();
});
Alright, now you have a partial form shown in a fancybox. This partial form is actually an Ajax.BeginForm. So when you submit this form it will send an AJAX request to the AddToBasket action and upon success it will update the <div id="SuccessBasket"></div> which is inside this form with the result returned by this action.

MVC & JQuery Multiple Views Multiple JqueryUI Elements

just a quick question about the mvc JqueryUI framework,
i have a _layout.cshtml page which initializes a set of tabs
i have a view which has a jqueryUI datepicker on it.
the View is loaded Dynamically into the tabs and displayed, but if i load a subsequent instance of the View on the Tabs then the datepicker will only populate the first instance of the datepicker.
my question is this
1. MVC uses independent Objects to create independent Views with the same ids as on the views
2. JQueryUI uses the XML Dom with Unique Ids to create its base objects
so how are these supposed to work together.
my View is as follows
<div class="PoCreate">
<div id="pnlProject">
<fieldset>
<legend>Project</legend>
<label for="ProjectNo">
Project #:
</label>
<input type="text" name="ProjectNo" id="ProjectNo" />
<input type="button" name="btnProjectNo" id="btnProjectNo" data-linked-search="#Url.Action("Project", "SearchObj")"
value=".." />
</fieldset>
</div>
</div>
#Url.Script("~/scripts/PageScripts/_PoIndex.js")
The Script file contains
$('.PoCreate').PoCreate({});
and the PO function contains
$.fn.extend({
PoCreate: function (opt)
{
$(this).each(function ()
{
var _self = $(this.parentNode),
_opts = {}, tabIdContext = $(this.parentNode).attr('id');
$.extend(_opts, (opt || {}));
$('.date', _self).each(function ()
{
$(this).attr('id', tabIdContext + '-' + $(this).attr('id'));
$(this).datepicker(Globals.Dates).keypress(function (e) { return false; });
})
$(':button').button().filter('[data-linked-search]').click(function (e)
{
$.extendedAjax({ url: $(this).attr('data-linked-search'),
success: function (response)
{
$('#dialog-form').find('#dialog-search').html(response).dialog(Globals.Dialogs);
}
});
});
});
}
});
I found a way to solve this,
On the Create of the JQuery Widget i have to rename the ID of the DatePicker field so that it is unique for the Tab created.
so my TabId = ui-tab-01
and DatePickerId = DatePicker1
renaming the DatePickerId so that it is now ui-tab-01-DatePicker1

Resources