Render different PartialViews onclick of different buttons - c#

I have a view which is supposed to show three different things depending on what button you click, aka what you are sorting after. At the moment, it's static, and the buttons don't anything. So, I have a main view called "Order", and in this View I want to render the partial views PartialOrderZero, PartialOrderQuantity and PartialOrders.
At the moment what I've got working is, inside my Order.cshtml:
<div class="orderListing">
#{Html.RenderAction("PartialQuantityZero");}
</div>
This works well, and I'm showing the data from my PartialView OrdersQuantityZero. Now, my goal is, onclick of different buttons, say button1, button2 and button3, render my three different PartialViews. It seems like it should be done through jQuery but the syntax I've tried doesn't work. Is there any way to set a placeholder where #{Html.RenderAction("PartialQuantityZero");} is at the moment, and render the different views with a $("#button1/2/3").click( function() { }?
Thanks in advance.

$('#button').on('click',function(){
$.ajax({
url: url,
type: 'GET',
success: function (data) {//data will be partial view
$('.orderListing').html(data)
}
});
})

Related

Refresh view component .net core RC2

I have one normal view with two views components inside. Normal view have also a button and the both views components have a button too.
How i can refresh the views components after clicking on button from normal view?
And how i can refresh second view component after clicking on botton from first view component?
I already tryed to find a way, but without success!
Best regards
Ultimately view components generate HTML markup when razor executes that code. If you want to update some part of your HTML page (like a partial page update), you may consider using jQuery and ajax to do that.
Something like this.
$(function(){
$("#SomeButton").click(function(e){
e.preventDefault();
//make the ajax call and get new data/markup for the
// div rendered by your first view component and update it
var url="TheUrlToActionMethodWhichReturnsPartialMarkup";
$("#DivIdA").load(url);
});
});
You can do the same thing for updating other parts of your page ( markup generated by view component 2) as well. Update the url to an action method which returns a partial view result.
I tried this:
`$("#buttonrefresh").on("click", function () {`
`$.ajax({`
`type: "GET",`
`url: '#Url.Action("VCTest")'`
`(function (result) {`
`$("#show").html(result);`
`});`
`});`
This script is to refresh one view component after clicking on button from normal view.
VCTest is the name of the view component.
show is the name of the div where the view component is called.

Send partial view model and Update partial view with jQuery has issues

I use partial view for small model inside other view model. so i send changes of it by grabbing model data from wrapper form and using serializeArray(). then return PartialViewResult from action and finally fill partial view div container by returned result. this is my code:
var modelStr = $("#[wrapperFormName]").serializeArray();
$.ajax({
type: "POST",
url: targetUrl,
cache: false,
data: modelStr,
success: function (sucResult) {
$('#pa_Cnt').html(sucResult);
},
fail: function (result) {
alert("Fail");
}
});
and render partialview in view as this:
#using (Html.BeginForm("[ActionName]", "[CtrlName]", FormMethod.Post, new { id = "[wrapperFormName]", #enctype = "multipart/form-data" }))
{
<div id="[partialcontainerName]">
#Html.Partial("[partialViewName]", [partialViewModelName])
</div>
}
One of issue is after update partial view with returned result don't work any of jQuery event handlers that bind to elements inside the partial and i know event handlers must be declare in main view and not in partial and handlers must be delegated.
Second issue is updated result has new values but some of elements in partial view show old values and i set cache of ajax to false as cache of action with [OutputCache(Duration = 0)].
I'm confusing. Can anyone help me.
Your first issue is because you must re-add your event handers. I assume you are adding your event handlers within $(document).ready or an equivalent when the page loads. After you've refreshed your partial using $.ajax, the original elements that had event handlers no longer exist - their instances have been replaced and therefore the event handlers won't fire. You need to re-add the event handlers as part of the success callback after the line:
$('#pa_Cnt').html(sucResult);
Not sure about the second issue..
I found it. Thanks from #David for first issue. I separate internal actions of delegated events to functions that pointed with variable names and attach delegate events to them after update html of partial with returned result. this is a simple sample:
var sampleHandler = function() { //some code }
and then in ajax success:
success: function (sucResult) {
$('#pa_Cnt').html(sucResult);
$("[parentClassNameSelector]").on("click", '[childSelector]', sampleHandler);
}
About second issue ModelState of MVC is Guilty. :) specially in elements that rendered by mvc helpers. So i decide to do this in controller action.
if (ModelState.IsValid) { ModelState.Clear(); }
I don't know if this is good or has any other issue. For now it was solved my problem. I'm waiting for new comments and advises. Thanks so much.

C# Kendo MVC Tabstrip post model in partial view

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.

How to send pre-formatted HTML elements from a WebMethod to jQuery

The title sort of explains what I'm trying to do.
The reason for this is that I am trying to implement infinite scrolling on my ASP.NET C# Website. I've previous accomplished the "effect" of lazy scrolling with the ListView Control but that was a dirty and 'slow' trick that used a DataPager and a couple of HiddenFields.
I would like to send a completely pre-formatted HTML element from a WebMethod to jQuery so that I can append it on the container <div>.
Actually what I need rendered in the WebMethod is a bunch of objects inside a container <div> that are similiar to the Facebook Wall. What I previous had was a ListView (B) nested in another ListView (A). A Single Each <ItemTemplate> from a single ListView had multiple ListViewItems of the other ListView. (A) Representing a wall post and (B) Comments bound to the Primary Key of (A).
Anyway, am I looking at this issue from the right corner or should I figure out some other way of doing this? Please share you thoughts.
Thank you.
You can just return a string from your webmethod with the html in it - and then pump it directly into an html element on your page on the 'success' function. NB I think this is the 'html()' element - or you can use .append(text);
Using JQuery
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetHTMLFormatted",
data: "{}",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").html(msg.d); // or .append(msg.d);
}
});
});
});
A better way to do it though is to return a JSON structure and use a template library to emit your html structure. See http://stephenwalther.com/blog/archive/2010/11/30/an-introduction-to-jquery-templates.aspx

.NET / jquery - previewing a form result/rendering a view to a string

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");
});

Categories

Resources