Ajax modal popup with modal binding from within partial view - ajax

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.

Related

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

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>

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.

MVC3 & Razor: How to structure forms & actions to allow for postback-like functionality?

I have a view with a drop down list. The default value for this is stored in a session variable. However, the user change change this, in which case new data is entered.
I have a change handler on the drop down:
#using (Html.BeginForm())
{
#Html.DropDownListFor(model => model.SelectedID,
new SelectList(Model.SelectValues, "Key", "Value",
Model.SelectedID), "", new { onchange = "this.form.submit()" });
... more fields ...
<input type="submit" name="Save" />
}
[HttpPost]
public ActionResult Index(ViewModel vm)
{
... decide if I update my data or save the changes ...
}
I tried wrapping the select in a separate form tag, but then the value of my SelectedID not updated in my view model.
How can I determine when the form is posted from a drop down change, and when it is posted from a button click?
If you don't want to reload the entire page when the user changes the selection of the dropdown you could use AJAX to silently trigger a request to a different controller action that will do the necessary updates. For example:
#Html.DropDownListFor(
model => model.SelectedID,
new SelectList(Model.SelectValues, "Key", "Value"),
"",
new {
id = "myddl",
data_url = Url.Action("update")
}
)
and then in a separate javascript file:
$(function() {
$('#myddl').change(function() {
var form = $(this).closest('form');
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: form.serialize(),
success: function() {
alert('update success');
}
});
});
});
and finally you could have a controller action responsible for the update:
[HttpPost]
public ActionResult Update(ViewModel vm)
{
... this will be triggered everytime the user changes some value in the
droipdown list
}
The simplest way would be to simply attach some behavior to those element's events and set a hidden field with the event target (which by now, should sound very familiar to __EVENTTARGET).
Like so:
$('#someButton').click(function()
{
$('#someHiddenField').val('someButton');
});
$('#someDropDown').change(function()
{
$('#someHiddenField').val('someDropDown');
});
And then your action method could inspect this value and act appropriately.
HOWEVER
It sounds like you're thinking in an outmoded concept for MVC. If you really needed some new information, you should consider using some Ajax and then having one of your action methods return a partial view if you want to update part of the page.

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"

MVC 3 Reload current page with modified querystring values

Background:
I have an MVC layout (master) view which uses #Html.RenderAction to display a dropdown in the left side navigation panel. This dropdown will be displayed on all the pages of the site.
The dropdown is wrapped in a form element and on change of the dropdown the form is posted.
Question:
Now, once the form is posted, I need to reload the contents of the current page (whatever page the user is currently on...) with the value of the dropdown attached in the querystring. This would mean replacing the value which might already be there in the querystring from a previous selection.
Example:
The user navigates to the Home page of the website:
Url: /Home/?dropdownvalue=blue
At this point the dropdown displays 'Blue' as selected. The user changes the value in the dropdown to 'Red'. I need to reload the page with the following url -
/Home/?dropdownvalue=red
The user moves to another page in the site:
Url: /CustomerFavorite/?dropdown=red
Change the value in the dropdown from 'Red' to 'Green'.
The 'CustomerFavourite' page should be reloaded with 'Green' in querystring.
I apologize for the lenghty post. But, thought of providing some extra information to clarify the issue.
Thanks.
Thanks to Darin for providing the link for javascript manipulation of the querystring. But, I wanted a server side solution so here's how I implemented it -
public ActionResult _ColorSelection(ColorModel model)
{
string selectedColor = model.Color.Value;
// Modify Querystring params...
NameValueCollection querystring =
HttpUtility.ParseQueryString(Request.UrlReferrer.Query); // Parse QS
// If Querystring contains the 'color' param, then set it to selected value
if (!string.IsNullOrEmpty(querystring["color"]))
{
querystring["color"] = selectedColor;
}
else // Add color key to querystring
{
querystring.Add("color", selectedColor);
}
// Create new url
string url = Request.UrlReferrer.AbsolutePath
+ "?" + querystring.ToString();
return Redirect(url); // redirect
}
You may try using a GET method of the form in which the drop down is wrapped:
#using (Html.BeginForm(null, null, FormMethod.Get))
{
#Html.Action("SomeActionThatRendersTheDropDown", "SomeController")
}
or maybe the entire form is wrapped inside the action:
#Html.Action("SomeAction", "SomeController")
and then in javascript subscribe to the change event of the dropdown and trigger the submission of the form:
$(function() {
$('#DropDownId').change(function() {
$(this).closest('form').submit();
});
});
Because you have used GET request, this will automatically reload the current page sending the value of the dropdown in the query string.
If you are using jQuery you can create a function that will post the selected value in your list.
$(document).ready(function () {
$("#ListId").change(function () {
$.ajax({
url: "CustomerFavorite/Edit",
type: "POST",
data: "colour=" + $("#ListId").val(),
success: function (result) {
//Code to update your page
}
},
error: function () {
}
}

Resources