How to load Different Partial Views on the same div by radio button selection? - ajax

enter code here
*MainView.cshtml*: #RadioButtonFor(m=>m.registeras,Individual) #RadioButtonFor(m=>m.registeras,BusinessEntity) <div id="loadpartial"> </div>
I have a register form in which User can register as Individual or Business entity. I kept two radio buttons.
If user selects Individual Radio Button, then that partial view should be loaded. if user selects Business entity radio Button then second partial view should be loaded on the same div.
I am new to asp.net mvc4 razor. Can someone please give the sample code.

You will have to use jQuery in order to make ajax calls.
First reference jQuery at the bottom of your page.
in your controller, define and implement a method which returns a partial view.
[HttpGet]
public ActionResult GetRegisterForm(int registeras)
{
if(registeras == Individual)
{
return PartialView("IndividualPartialViewName");
}
else
{
return PartialView("BusinessPartialViewName");
}
}
Now in your view, you can call the above action using ajax.
<script type="text/javascript">
$(function(){
$("[name=registeras]").on('change', function(){
var $radio = $(this);
$.ajax({
url:'#Url.Action("GetRegisterForm", "ControllerName")',
data: { registeras = $radio.val() }
type: 'GET',
success: function(data){
$("#loadpartial").html(data);
}
});
});
</script>

Related

Ajax modal popup with modal binding from within partial view

I am trying to find a solution for a while but could not find one... I have partial view which is bound to a modal and it displays data in grid. Something like below
#model abc
#Html.Grid(Model)
{
grid columns
column with edit link
}
on the click of edit link from a grid, through ajax, I would want to display popup window in partial view which is bound to another model. This bootstrap popup window should also be bound through model binding as I need to perform server side validations when click on Submit of popup
#model pqr
<div>
popup window with grid columns displayed in form for editing.
</div>
Any help with sample code would help tremendously.
There are probably other ways to do this but I have done like this before:
Your edit link must have id as the id to be passed as param to Controller
Get data and pass the model to the partial view with properties populated
$(".YourEditLinkClass").click(function () {
var id = $(this).attr('id');
$.ajax({
url: "#Url.Action("GetDataForPopUpWindow", "YourController")",
type: "GET",
dataType: "html",
data: { id: id },
success: function (data) {
$("#modal_" + id).html(data);//target position of modal
$('#pqr_' + id).modal('toggle');
}
});
});
Controller code:
public ActionResult GetDataForPopUpWindow(int id)
{
using (YourDBContext)
{
var data = YourData;
pqr pqrModel = new pqr();
pqrModel.YourModelProperty = data.CorrespondingProperty;
return PartialView("_GridPartialView", pqrModel);
}
}
Your bootstrap modal must have the id as id="pqr_#Model.Id" in the partial view called _GridPartialView. Hope it makes sense.

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?

Is there a way to use AJAX on a DropDownList changed event to dynamically modify a partial view on a page?
My main page has a DropDownList (DropDownListFor) and a partial view which ONLY contains a list of "items". The items shown in this partial view are dependent upon the item selected in the DropDownList. There's a 1 to many relationship between the DropDownList item and the items in the partial view. So, when the user changes the value of the DropDownList, the content in the partial view will dynamically change to reflect the item selected in the DropDownList.
Here's my DropDownList:
<div data-role="fieldcontain">
Choose Capsule:<br />
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules" })
<br />
</div>
Here's my Partial View declaration on the same page:
<div data-role="fieldcontain">
#Html.Partial("_FillerPartial", Model.Fillers)
</div>
I'm not very familiar with Ajax, but looking at other examples, here's what I have for my Ajax:
$(document).ready(function () {
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
alert("server returned: " + data);
}
});
});
});
And finally, here's a screenshot of what's going on. By changing the "Choose Capsule" drop down list, I want the Filler list to update dynamically:
You can load the drop down list as a partial view from the controller using ajax.
The controller code:
[HttpGet]
public virtual ActionResult GetFillersByCapsule(string cappk)
{
var model = //Method to get capsules by pk, this returns a ViewModel that is used to render the filtered list.
return PartialView("PartialViewName", model);
}
The main view html:
<div id="filteredList">
</div >
The partial view
#model IEnumerable<MyCapsuleModel>
foreach (var x in Model)
{
//Render the appropriate filtered list html.
}
And you can load the filtered list using ajax:
$('#ddlCapsules').change(function () {
// make ajax call to modify the filler list partial view
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
$("#filteredList").empty();
$("#filteredList").html(data);
}
});
});
Hope this helps.
You can't update the partial, per se, because the partial will never be rendered again without a page reload. Once you receive the HTML, ASP is done, you're on your own at that point.
What you can do, of course, is switch out the content of a particular div or whatever using JavaScript. Your example in particular screams Knockout, so that's what I would recommend using.
Change your HTML to add a data-bind to your containing div:
<div data-role="fieldcontain" data-bind="foreach: filler">
<button data-bind="text: name"></button>
</div>
And your DropDownList:
#Html.DropDownListFor(x => x.CapsuleFK, new SelectList(Model.Capsules, "pk", "name", "pk"), new { id = "ddlCapsules", data_bind = "event: { change: updateFillers }" })
Then, some JavaScript:
var FillersViewModel = function () {
var self = this;
self.fillers = ko.observableArray([]);
self.updateFillers = function () {
var selection = $('#ddlCapsules').val();
var dataToSend = { cappk: selection };
$.ajax({
url: 'Process/GetFillersByCapsule',
data: { cappk: dataToSend },
success: function (data) {
self.fillers(data.fillers) // where `fillers` is an array
}
});
}
}
var viewModel = new FillersViewModel();
ko.applyBindings(viewModel);
This is a very simplistic example, and you'll need to do some more work to make it do everything you need it to do in your scenario, but the general idea is that every time the dropdown list is changed, Knockout will call your updateFillers method, which will execute the AJAX and put new data into the fillers observable array. Knockout automatically tracks changes to this array (hence the "observable" part), so an update is automatically triggered to any part of your page that relies on it. In this scenario, that's your div containing the buttons. The foreach binding will repeat the HTML inside for each member of the array. I've used a simple button element here just to illustrate, but you would include the full HTML required to create your particular button like interface. The text binding will drop the content of name in between the opening and closing tag. Refer to: http://knockoutjs.com/documentation/introduction.html for all the binding options you have.
There's much more you could do with this. You could implement templates instead of hard-coding your HTML to be repeated in the foreach. And, you can use your partial view to control the HTML for this template. The important part is that Knockout takes the pain out of generating all this repeating HTML for you, which is why I recommend using it.
Hope that's enough to get you started.

Dynamically load Partial Views

How can i dynamically load a Partial View?
I mean I have this view, lets say ListProducts, there I select some dropdownlists with products, etc, and with the selected values from those I wanna fill a partial view, which would be in a div that was invisible but after onchange() event would become visible and with the data from the specific selected items.
Use jQuery's $.load() with a controller action that returns a partial view.
For example:
HTML
<script type="text/javascript">
$(document).ready(function()
{
$("#yourselect").onchange(function()
{
// Home is your controller, Index is your action name
$("#yourdiv").load("#Url.Action("Index","Home")", { 'id' : '123' },
function (response, status, xhr)
{
if (status == "error")
{
alert("An error occurred while loading the results.");
}
});
});
});
</script>
<div id="yourdiv">
</div>
Controller
public virtual ActionResult Index(string id)
{
var myModel = GetSomeData();
return Partial(myModel);
}
View
#model IEnumerable<YourObjects>
#if (Model == null || Model.Count() == 0)
{
<p>No results found</p>
}
else
{
<ul>
#foreach (YourObjects myobject in Model)
{
<li>#myObject.Name</li>
}
</ul>
}
You can do this by following these steps. In your controller, you return a partial view.
[HttpGet]
public virtual ActionResult LoadPartialViewDynamically()
{
var query = _repository.GetQuery();
return PartialView("_PartialViewName", query);
}
then in the view you have an empty div
<div id="partialgoeshere"></div>
and then load the partial view using jQuery:
function LoadPartialView() {
$.get("#Url.Action(MVC.ControllerName.LoadPartialViewDynamically())", { null }, function (data) {
$("#partialgoeshere").empty();
$("#partialgoeshere").html(data);
});
}
Hope this helps
I believe you can do something like this example, just using the change event on your dropdown instead. It's a simple jQuery call, you can find more on the jQuery website.
$("#dropdown").change(function() {
$("#destination").load("/Products/GetProduct", $(this).val(),
function(result) {
// do what you need to do
});
});
The first parameter is the view you need to call for the details.
The second parameter is the selected value.
The third parameter of the $.load function is the callback function, where you can parse the result and do what you need to do.
If you have a multiple select $(this).val() that will give you an array with the selected options.
If you want only return a Json object you may want to follow this example.
Use Ajax :)
http://api.jquery.com/jQuery.ajax/
Example:
$.post(window.gRootPath + "Customer/PartialView", { Question: questionId})
.done(function (data) {
$('#partialDiv').html(data.responceText);
});
You can use ajax to call action an then just insert html string using jQuery to the page where you want it to appear:
Server-side:
Render partial view to string
Renders partial view on server to html string, useful when you need to add partial view to ASP.NET MVC page via AJAX.
Client-side:
$('#yourDdl').change(function()
{
$.get('/InsertPartialViewUsingAjax', function (data)
{
$('#container').html(data);
});
});
The following article tells you how to do it with minimum javascript. Basically you return html instead of JSON to your response object.
https://www.simple-talk.com/content/article.aspx?article=2118

partial view not opening as jQuery UI Dialog

I need to open a partial view as dialog box on click of a button, basically add/ Edit scenario. My problem is that mu partial view does open but not as a dialog but at the bottom of the page.
Please see my code below:
I have an empty div on the page:
On the click of the button I call the below code:
function addSelectionActivate() {
var selectionID = 0;
$.ajax({
url: "AddEditSelection",
type: "POST",
data: "&selectionID=" + selectionID,
dataType: "html",
success: function (data) {
$("#addEditSelectionDialog").html(data);
$("#addEditSelectionDialog").dialog('open');
},
error: function (error) {
alert(error.status);
}
});
}
My controller has a method "AddEditSelection" which returns the result. But the partial view opens at the end of the page rather than as a dialog. Please help what I might b edoing wrong.
you need to add the partial in a seperate div contained in the dialog div.
eg:
<div id="DialogDiv">
<div id="AnotherDiv">
</div>
</div>
and register "DialogDiv" as dialog and load ur partial in the "AnotherDiv"

Choosing between Ajax and full Postback at runtime

I have an MVC 3 view for rendering reports from SQL Server Reporting Services. There's a form at the top where I capture parameters for the report and on submission, my controller action is dutifully called and my report is rendered into a < div >.
I'm now adding an Export to Excel function. I want the same parameters from the form, but this time, I want a full Postback, not an Ajax call to the controller, so that the user is offered the opportunity to download the report. Otherwise, my report gets rendered as binary content on the existing view.
I'm thinking that I want to be able to switch the behaviour of my form between Ajax and normal Postback, depending on which 'submit' button I click.
Any ideas?
#using (Html.BeginForm("Export", "Report"))
{
... some form fields
#Html.ActionLink("Render report", "Render", "Report", null, new { id = "generateReport" })
<input type="submit" value="Export to Excel">
}
<div id="report"></div>
and then AJAXify the Render report link in a separate js file:
$(function() {
$('#generateReport').click(function() {
var form = $(this).closest('form');
$.post(this.href, form.serialize(), function(result) {
$('#report').html(result);
});
return false;
});
});
and in your ReportController you would have both Export and Render actions.

Resources