JQuery doesn't work in partial view i can't fix - c#

When i click button jquery doesn't work in partial view
here is code
Controller
public PartialViewResult Chat()
return PartialView();
}
Button
<input id="button" type="submit">
Render In HTML
<div id="test">
#{Html.RenderPartial("Chat");}
</div>
Javascript
$('#button').live('click', function () {
$('#test').load('#Url.Action("Chat")');
});

Several possible reasons most likely including:
you didn't include jQuery library at all
you didn't call $('#button').live() in a $(document).ready() statement

jQuery initialisation is done to all matching elements in the document at the time of running. If you are dynamically loading your partial view after the initialisation, new elements matching the filter will not be automatically initialised. You will need to run the jQuery initialisers again after the .load is complete.
This will also double up existing matching elements' events so you need to run them using the container div to restrict the elements that will be affected.
$('#test').find('xxxxx').click(function.....

Related

Dynamically adding to a page with MVC

I have a Razor View which has a section where the user can add new rows for ad-hoc opening/closing times on specific dates. It consists of three controls - a DatePicker, two Select lists and a "delete row" button. Existing saved rows are rendered on page-load through Razor, and any new rows are added via an OnClick event and JavaScript appending largely fixed html to the DOM element. All rows are then saved (or removed as required) on HTTPPost.
I have a new requirement which requires implementation of a much more complicated data-set for these ad-hoc, "user-generated" rows. The HTML for each of these rows is extensive. Is there a more elegant way of injecting Razor within a View on a button click than appending hard-coded HTML in JavaScript?
This depends entirely on your use case, and you did not provide any code in your question, but there's something called Partial View. You can read a basic introduction here.
For your case, I'd do something like this:
Controller
public IActionResult GetNewRow()
{
return PartialView("_NewRow");
}
View
<button id="btnAddRow" class="btn btn-primary">Add new row</button>
<script type="application/javascript">
$(function() {
$("#btnAddRow").on("click", function () {
$.get("/GetNewRow", function success(data) {
$("#WHEREVERYOUAREADDINGROWS").append(data);
});
});
});
</script>
PartialView (_NewRow)
<tr>
<td>Add whatever you need here</td>
<tr>
Note: I didn't try this so the AJAX syntax might be a little off.

ASP.Net MVC 5: Html.RenderAction("...") at runtime

I want to add a PartialView multiple times by pressing a button.
<div id="FilterRows">
#{Html.RenderAction("_FilterRow");}
</div>
<button id="newRow" type="button"
class="btn btn-sm btn-default"
style="width: 50px">+</button>
This piece of code works properly. But now i want to append the div FilterRows with another PartialView of _FilterRow at clicking on the button.
This is how it looks today:
Something like:
$(document).ready(function() {
$("#newRow").click(function() {
$("#Exec").append("<br>", #{Html.RenderAction("_FilterRow");} {
});
});
});
Is unfortunately not working. Any Ideas?
If you add an action which returns the partial rendered as a partial (ie. return PartialView("myView", model); then you can load using jQuery:
# Create a new element to contain...
var el = $('<div></div>');
$('#parent').append(el);
# ...the new content
el.load('#Url.Action("action", "controller"');
(This means running the JS in the razor view to get the correct URL generation. If most of the JS is in its own file, pass the URL from a little JS in the Razor file just for things like URLs.)
As long as your script is in the page (and not in an external .js file) you can use Razor inside js (although feedback directly from MicroSoft indicates that this is "unexpected", it works fine).
Have a look at the rendered html to see what's wrong.
In this case you need quotes (") around the render action:
$("#FilterRows").append("#{Html.RenderAction("_FilterRow");}");
This assumes a number of potential issues:
the 'RenderAction' can't have any newlines in the output
the 'RenderAction' can't have any quotes in the output (either use ' on the append and " inside the render or the other-way-around)
the action to be rendered cannot have any row-specific parameters (which appears to be ok in this case to add a new blank row)
the script must be in a .cshtml file (though you can get around this by setting a global/namespace'd variable in the .cshtml and have the actual code in a .js file)
you need to use the correct combination of #{}/#() and render/tostring
You might be better off with #Html.RenderPartial if you just want to render some html and don't need an action.
An alternative, perhaps more friendly, mechanism would be to have the blank-row already on the page (perhaps hidden) and use .clone().

Best way to display a JQuery Dialog with ASP.NET MVC data bound View Model

Imagine a simple page with a list of users. Selecting a user displays a JQuery modal dialog with various details that can be edited. Something like:
#model IEnumerable<UserRole>
#if (Model.Any())
{
foreach (var user in Model.Users)
{
Details
}
}
I'll have more specific examples through the post but what I'm looking for is a general 'experienced' opinion on what's the best way to load and display a Model bound Partial View as a JQuery dialog box.
I know how to do it code-wise but I think there must be a better way. I believe the common known ways to do it are not very efficient.
My rule and what I would like is for all code associated to a partial view popup to be kept in that partial view. I would like my popup to be structured something like the following UserDetails partial view:
#model User
<script src="#Url.Content("~/Scripts/UserScripts.js")" type="text/javascript"></script>
<div id="placeholder">
...The modal dialog content...
</div>
This way when another developer gets to look at it one will easily be able to piece it all together.
So as far as I know there are two ways to display a partial view as a Dialog and I have a problem with both of them:
1) Use the Partial view structure I displayed above, pre-load the div dialog from the master page by using #Html.Partial("UserDetails", new User) and then, when I need the dialog to be displayed populated with user data execute an Ajax call to an ActionMethod that will re-populate the partial view's model with needed data and re-render it with JQuery .html() method.
Once the partial view/dialog is loaded with data I simply display it with JQuery .dialog('open')
Great, this works but there are a few problems with this logic:
a) I'm loading the same partial view twice ( first blank , second loaded with data )
b) Content of the Placeholder DIV flashes on the screen when the master page is being loaded. Setting DIV to display:none won't work here before when .html() method triggers it will load the partial view with that display:none tag in it and the popup will be presented as a blank window.
c) When the page is requested, if large, it takes some time for the page to show
2) Instead of having in the partial View I can place a blank <div id="placeholder"></div> on the master page and then load the partial view content into that div with ajax or as I'm doing it now with JQuery :
var url = "/MyController/MyAction/" + Id;
$("#palceholder").load(url).dialog('open');
Again, it works but there are a few big problems I see with this way:
a) It breaks my "keeping it all together rule". When looking at , without some searching around another developer will have no idea what partial view will be loaded in this Div.
b) All Javascripts for the partial view popup will now need to be referenced in the master page, instead of a the partial view itself.
c) When the page is requested, if large, it takes some time for the page to show
The bottom line question is what do you think is the best way to display the model-bound populated partial view as a Modal Dialog while keeping the code organized ?
My perfect scenario would be to pre-load all partial view fields and then, when the request is made for the dialog to show populated with Data somehow a model bind pre-loaded partial view to the new JSon set of data, without loading/re-loading all partial view fields.
Is there a way ?
P.S. One of the things I tried is to pre-load my partial view fields with #Html.Partial("UserDetails", new User) and then use JQuery .replaceWith() method to replace Div contents but I couldn't get it to work unfortunately.
Any thoughts are appreciated. No ideas as are bad ideas.
Thanks.
Nothing wrong with having part of your code load in partial, and then just updating the partial container with a return from action.
<div id="ParitalContainer">
#Html.Partial("_PartialView", Model.PartialModel)
</div>
Or, you can consider a scenario to work with JSON data. Namely, have all your data loaded async by calling a $.ajax or $.getJSON. Your action result would return JsonResult and then you can just update the elements you want.
Furthermore, you could look into using Knockout.js if you want more robust solution. This is what I would do if I wanted "keeping it all together" approach.

return PartialView with Ajax not inserting on page

Just trying to wrap my head around the Ajax helper in Razor -- Probably overlooking something simple.
The following code is directing my current tab to /Music/SearchBand rather than returning the partial to my div.
I've got this in my View:
#Ajax.ActionLink("click me","SearchBand",
new AjaxOptions {
UpdateTargetId = "replaceThisDiv"
})
<div id="replaceThisDiv"></div>
And this in my controller:
public ActionResult SearchBand()
{
return PartialView("_bandResults");
}
The #Ajax. ... helpers jut add some additional data- attributes to the generated HTML which in itself won't do any ajax requests (that's why the link "just" navigated to a different page).
To make it work porperly it needs some client side javascript functions which will fire the actual ajax requests with the use of the pregenerated data- attributes.
These js functions are in the Sripts/jquery.unobtrusive-ajax.min.js file:
So you need to include this JS file on every page where you plan to use any of the #Ajax. ... helpers:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>

How can I add extra partial views, depending on a dropdownlist selection, in ASP.NET MVC and jQuery?

I have a form to which I want to add extra fields depending on the value of a dropdown list. They would be sets of fields and I was thinking on dynamically changing a div's content with the html from a render partial, which would render a PartialView with the fields I want.
Right now the code for the drop down list is the following
<p>
<label for="CatalogItem.Type"> Type: </label>
<%=Html.DropDownList("CatalogItem.Type",Model.Types, "Choose Type") %>
</p>
<div id = "ExtraInfo">
</div>
And I want to put the extra stuff (fields specialized for the type) in the ExtraInfo div. What would the jQuery code be for this?
Thanks!
#Tony has the right approach but instead of putting your RenderPartial html right into the ".html("add html code inside div here")" you may want to do an ajax call. That way the user isn't downloading a bunch of html he/she may not even see.
something like so:
if ( myval == "someValue")
{
$("#ExtraInfo").load("/dynamic-stuff/1")
}
else if ( myval == "someOtherValue")
{
$("#ExtraInfo").load("/dynamic-stuff/2")
}
This also assumes you have a route set up to handle a url like "/dynamic-stuff/2" and responds with the correct partial view.
First add a css class selector to your dropdown, lets call it 'mydropdown' for now
use something like this:
<script language=”javascript” type=”text/javascript” >
function addtoDiv()
{
$(document).ready(function() {
var myval=$(”#mydropdown”).val(); // get value of dropdown
if ( myval == "somevalue") // check myval value
{
$("#ExtraInfo").html("add html code inside div here"); // add code based on value
}
}}
</script>
Do you need to dynamically add fields? You can add fields with JQuery by doing:
$("").attr("id", "test").addClass("FormLabel").appendTo("#parentElement");
$("").attr("id", "testinput").attr("type", "text").appendTo("#parentElement");
In this way, you can create the fields programmatically.
As an alternative, you can create a JQuery partial view. Create an action method that returns an instance of this partial view, and call that action method using
$.get("/<controller>/<actiontoreturnpartialview>", function(data) {
$("#ExtraInfo").html(data);
});
It makes it easier because then you can rely on server-side logic to render the UI, though I tend to use the client-side approach.
Alternatively, you can create your own HTML helper to do this all, but that would be a lot of work.
HTH.

Categories