JQuery function attached to Ajax ActionLink - c#

Quick question.
I have a Ajax.Action link intended to upload the next section of a form asynchronously.
#Ajax.ActionLink("Next" , "matches",null, new AjaxOptions {UpdateTargetId = "placeholder", InsertionMode = InsertionMode.InsertAfter,HttpMethod = "GET"}, new { #class = "button" })
I've applied my "button" class to it, which gives it the appearance of a big button.
I'm looking to attach a JQuery .click event to the above AjaxAction link triggering a function that will hide the previous form. I'm using the JQuery below to do so:
<script>
$(document).ready(function () {
$(this).closest("a.button").click(function () {
$("form.common").hide();
});
});
</script>
This is not working for me. The Ajax.ActionLink works fine, just not the Jquery. Below is rough breakdown of my page.
<form class="common"> (this form needs to hide)
//lots of inputs
<ActionLink class="button>
</form>
<div id="placeholder">
(this is where the new form will be inserted)
</div>
I'm new to C# and JavaScript/JQuery, so I'm hoping someone can point me in the right direction here.

Rather than using any special events with jQuery, you could call a JS method in the beginning of ajax request performed by ajax link.
Add OnBegin property in your link AjaxOptions and assign a JS function into it and do the logic in that JS function
Ajax Link
new AjaxOptions { OnBegin = "OnBegin" ... }
JS
function OnBegin() {
$("form.common").hide();
}
Hope this will help !!

Try to target your element directly instead of using closest. If you can also use the buttons id or assign a more descriptive class.
$("a.action_button").click(function () {
$("form.common").hide();
});

Related

Loading JQuery in Partial View on MVC

I have an ASP.NET MVC C# web application.
In my layout file I have the following ajax call
<li class="PriceModal">
#Ajax.ImageActionLink("/InternalDB/Content/downloadCSV.png", "Pareto", "35px", "35px", "PartialViewPriceCalculator",
"PriceCalculator", new {#Pareto = "active" }, new AjaxOptions
{ UpdateTargetId = "PriceCalculator", InsertionMode = InsertionMode.Replace, HttpMethod = "GET"}, new { #style = "padding-top:30px" })
</li>
When this Ajax link is clicked a bootstrap Modal is loaded and a partial view is load inside the Bootstrap Modal. At this point the Bootstrap modal and the partial view inside are sitting on top of my existing page.
My problems start when I place jQuery code inside the partial View. I have found a way to append the jQuery code (partial) to the DOM with the following code
$('body').on('jQuery event to be placed here(focus,change,mouseenter)', 'class/ID to be Placed here', function (e) {
// jQuery events
});
This will allow me to append to the DOM loaded by my page on the background.
However this has a lot of issues as well. How do I append a jQuery plug in called Chosen to a dropdownlist which is sitting inside my partial view.
I have experimented by putting the jQuery inside the Ajax Options and using the Onsuccess property but this seems to have problems as well.
<li class="PriceModal">
#Ajax.ImageActionLink("/InternalDB/Content/downloadCSV.png", "Pareto", "35px", "35px", "PartialViewPriceCalculator",
"PriceCalculator", new {#Pareto = "active" }, new AjaxOptions
{ UpdateTargetId = "PriceCalculator", InsertionMode = InsertionMode.Replace, HttpMethod = "GET", OnSuccess = "$('.chosen2').chosen({ allow_single_deselect : true })"}, new { #style = "padding-top:30px" })
</li>
Is there a general approach to loading all of the needed jQuery inside a popup partial view or i just need to find hacks for each specific situation?
You can just use the document.ready event to execute JavaScript when your PartialView finishes loading:
<div id="partialViewHere">
</div>
<script type="application/javascript">
$(function() {
// load whatever you need here
};
</script>
I use this on an application to add events to buttons loaded through different PartialViews and it works perfectly.

MVC5 simple ajax request stuck

iv read several posts about ajax calls and im still confused.
My HomeControler got methods
public async Task<ActionResult> Index(string srchterm)
public async Task Publish(TrendVM trendVm)
I want to call Publish it from index.cshtml
my view is like this
#model IEnumerable<Trend>
<div class="container-fluid post-container">
#if (Model != null)
{
foreach (var trend in #Model)
{
Html.RenderPartial("_Trend",trend);
//button that calls Publish and passes it trend without refreshing the page.
}
}
</div>
is the some razer helper that will generate the request?
Recommended approach
If you have a unique record id for each trend item you are printing, you should use that id to pass it back to your server via ajx.
foreach (var trend in #Model)
{
Html.RenderPartial("_Trend",trend);
#Html.ActionLink("Publish","Publish","Home",new { id=trend.Id},
new { #class="publishLink"})
}
Basically, the above code will render an anchor tag like this for each trend item
Publish
where 450 will be replaced with the actual unique Id you have for trend item. Clicking on the link will open the url in a new page usually. I don't think you want that to happen here. So we will override the default click behaviour and make an ajax call to server.
Add this script to your page
#section Scripts
{
<script>
$(function(){
$("a.publishLink").click(function(e){
e.preventDefault();
var url=$(this).attr("href");
$.post(url,function(response){
alert("Publish completed");
});
});
});
</script>
}
Now we need to make sure our publish method accepts an id and do the processing. So change the Publish method to /Create a new method (and use that method name in our earlier markup in Html.ActionLink call)
public async Task Publish(int id)
{
// using the Id value, do some processing.
}
But if you do not want to change your Publish method signature, what you should be doing is creating a form inside your foreach loop and serialize the form and send it. You need to keep the data you want to send in input form fields. We will keep those in hidden fields for now.
foreach (var trend in #Model)
{
Html.RenderPartial("_Trend",trend);
using(Html.BeginForm("Publish","Home"))
{
#Html.HiddenFor(s=>s.Name)
#Html.HiddenFor(s=>s.TrendCode)
#Html.ActionLink("Publish","Publish","Home",new { id=trend.Id},
new { #class="publishLink"})
}
}
Assuming Name and TrendCode are 2 properties of your TrendVM.
and the javascript will be
#section Scripts
{
<script>
$(function(){
$("a.publishLink").click(function(e){
e.preventDefault();
var _f=$(this).closest("form");
$.post(_f.attr("action"),_f.serialize(),function(response){
alert("Publish completed");
});
});
});
</script>
}
You should write some js code. And use $.ajax() function. Put a button on your View:
<button id="your-submit-button" type="submit">Ajax call</button>
Put empty div somewhere on page where you will put your PartialView:
<div id="your-partial-view-container"></div>
Then put some jquery (you also can use plain old js, but it's easier with jquery) on your page. It's better to put all your js code in #section script {} that defined in your _Layout:
$(document).ready(function() {
$("#your-submit-button").click(function(){
$.ajax({
url: #Url.Action("Publish","Home"), //here you put your controller adress
type: "POST",
dataType: 'html',
data: $("#your-form-with-model-data-id").serialize(), //that's how you get data from your form to send your TrendVM to controller
success: function(data) {
$("#your-partial-view-container").html(data);
}
});
});
});
Now when you click on button your js code should be call controller and response will be added inside your div.

Link Dynamic URL to div in Umbraco

I am building a site using Umbraco and I have a div that currently has a link inside it. The current code is:
<div class="callout col-sm-4 leftCtaLink">
<p>#CurrentPage.leftDescription</p>
<a class="primary-bg" href="#CurrentPage.leftCtaLink"><img class="svg-inject" src="#Umbraco.Media(CurrentPage.leftIcon).umbracoFile" alt="Icon" />#CurrentPage.leftCtaText</a>
</div>
This works and only the bottom half of the callout links to the correct page. The client wants the whole div to be linkable now though, so I thought I'd do this with jQuery. Here is that:
<script type="text/javascript">
$(document).ready(function () {
$(".leftCtaLink").click( function() {
window.location=$(this).find("a").attr("#CurrentPage.leftCtaLink");
return false;
});
});
</script>
The issue is, that when the div is clicked on, it takes me to the website's url with /undefined at the end of it. Can anyone tell me what I need to change in the JS to have it use the correct URL that was input in the CMS?
Change to attr("href").
$(document).ready(function () {
$(".leftCtaLink").click( function() {
window.location=$(this).find("a").attr("href");
return false;
});
});

Jquery datepicker is not working in MVC?

Here i am using a jquery datepicker from this sample http://dev.jtsage.com/jQM-DateBox2.
It is working fine but the problem is after clicking the submit button if there is any mandatory field validation error,the next time when i click the textbox jquery datepicker is not working means the script is not loading after submit click.it is throwing the error in firebug console like
TypeError: $(...).datebox is not a function
$('#txtstartdate').datebox('open');
Here is my code
$(document).ready(function () {
$('#txtstartdate').live('click', function () {
$('#txtstartdate').datebox('open');
$("#txtstartdate").datebox("option", {
mode: "calbox",
highDatesAlt: ["2011-11-09", "2011-11-10"],
highDates: ["2011-11-02", "2011-11-03"],
pickPageOAHighButtonTheme: "b"
});
});
});
and
#Html.TextBoxFor(m => m.StartDate, new { #name = "mydate", #id = "txtstartdate", style = "height:20px; font-size:10px;", data_role = "datebox", data_options = "{\"mode\":\"calbox\",\"useButton\": false}" })
Any suggestion?
as the firebug error suggest the browser could not find the function being used within the script can you make sure that the dependencies of the datebox is availiable after the submit call.
also try to send the dependencies with the view itself so that on every rendering of the view page at the client end it hold these js file with in it.

Dropdownlist box in asp.mvc 2 and jquery [duplicate]

I have a code block in my MVC view as follows:
<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
{ %>
<%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
<%} %>
I want to set the value of ViewData["selected"] so that i can send it to the desired action.
Can anyone please suggest how can i do this?
thanks!
Instead of using a form, why not use a jQuery onChange event on your drop down?
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).
Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.
Found solution at this post it is just small chnge
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”

Categories

Resources