As you can see I am using data attributes to load the div DataSet_Data with a partial view returned from that url.action.
It loads on page load correctly hitting the data-url and loads the correct partial view.
What I am trying to do is when the dropdownlist is changed to reload the div with the updated data-url action
url = url + '/DataSetID=' + $(this).val();
the first console.log for the original data-url attribute is /CP/Data/DataSetID=3
the console.log for url shows /CP/Data/DataSetID=4 when the drop down is changed.
the data-ajax is switched to false correctly
the updated data-url shows as/CP/Data?DataSetID=4 correctly set
and the DataSet_Data click function shows the click when changed.
<div class="row form-group">
<div class="col-lg-2">
</div>
<div class="col-lg-3">
#Html.DropDownListFor(m => Model.DataSetID, new SelectList(Model.DataSets, "Value", "Text"), htmlAttributes: new { #class = "form-control m-l-5", #id = "selectedDataSet" })
</div>
</div>
<div id="DataSet_Data" data-ajax="true" data-url="#Url.Action("DataSet_Data", "CP", new { DataSetID = DataSetID })">
</div>
}
<script>
$(document).ready(function () {
console.log($('#DataSet_Data').attr('data-url'));
$("#selectedDataSet").change(function () {
var url = '#Url.Action("DataSet_Data", "CP")';
url = url + '/DataSetID=' + $(this).val();
console.log(url);
$('#DataSet_Data').attr('data-ajax', false);
$('#DataSet_Data').attr('data-url', url);
console.log($('#DataSet_Data').attr('data-ajax'));
console.log($('#DataSet_Data').attr('data-url'));
$('#DataSet_Data').click();
});
$('#DataSet_Data').on("click", function () {
console.log("click");
});
});
</script>
I need the code to reload the div using the updated data-url.
Im sure im missing something easy or there may be an easier way to achieve this.
<script>
$(document).ready(function () {
$("#selectedDataSet").change(function () {
var url = '#Url.Action("DataSet_Data", "CP")';
url = url + '?DataSetID=' + $(this).val();
$("#DataSet_Data").load(url);
});
});
</script>
This solved the issue.
Related
I have a problem changing items after searching.
I looked at similar threads but found no solution there :(
It looks like the first time the page loads well - the first time the entire Index.cshtml page is loaded which contains a collection of books in the selected category.
There is a search engine on the page - after searching for "manual" - ajax correctly replaces elements with those containing "manual" in the name.
Then when I enter something into the search engine a second time (for example "exercises") - the content of the page does not change any more.
I tried to debug and I see that new items are correctly downloaded from the database - the condition "if (Request.IsAjaxRequest ())" is true and the items are passed to partial view - there the "foreach" loop goes through them. Unfortunately, after _Partial, nothing happens.
I can't find a mistake - the strangest thing is that the first ajax call works fine - only the second (and subsequent) bad.
CatalogController.cs
public ActionResult Index(string categoryName = null, string searchQuery = null)
{
if (categoryName == null)
categoryName = (db.Categories.Find(1)).Name;
var category = db.Categories.Include("Books").Where(x => x.Name.ToLower() == categoryName).Single();
var books = category.Books.Where(x => (searchQuery == null || x.Title.ToLower().Contains(searchQuery.ToLower()) || x.SubTitle.ToLower().Contains(searchQuery.ToLower()) || x.Level.ToLower().Contains(searchQuery.ToLower())) && !x.Inaccessible);
if (Request.IsAjaxRequest())
return PartialView("_PartialBooksList", books);
else
return View(books);
}
Index.cshtml
<form class="o-search-form" id="search-form" method="get" data-ajax="true" data-ajax-target="#booksList">
<input class="o-search-input" id="search-filter" type="search" name="searchQuery" data-autocomplete-source="#Url.Action("SearchTips")" placeholder="Search" />
<input class="o-search-submit" type="submit" value="" />
</form>
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
#section Scripts
{
<script src="~/Scripts/jquery-3.5.0.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script>
$(function () {
var setupAutoComplete = function () {
var $input = $(this);
var options =
{
source: $input.attr("data-autocomplete-source"),
select: function (event, ui) {
$input = $(this);
$input.val(ui.item.label);
var $form = $input.parents("form:first");
$form.submit();
}
};
$input.autocomplete(options);
};
var ajaxSubmit = function () {
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function (result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
return false;
};
$("#search-filter").each(setupAutoComplete);
$("#search-form").submit(ajaxSubmit);
});
</script>
}
_PartialBooksList
#model IEnumerable<ImpressDev.Models.Book>
#using ImpressDev.Infrastructure
<div class="row">
#foreach (var book in Model)
{
<div class="col-12 col-xl-4">
<a class="o-shop-link" href="#Url.Action("Details", "Catalog", new { bookId = book.BookId })">
<div class="o-shop-item">
<img class="o-shop-img" src="#Url.BookPhotoSourcePath(book.PhotoSource)" />
<div class="o-shop-text">
<h2>#book.Title</h2>
<h6>#book.SubTitle - #book.Level - <b>#book.Price zł.</b></h6>
+ Add to cart
</div>
</div>
</a>
</div>
}
</div>
Please help
I am not sure if this is the case, but try to change this code:
$($targetElement).replaceWith($newContent);
To this:
$($targetElement).html($newContent);
I think the problem is the div element with id="booksList" is replaced after first search. So you don't have this element in the second search.
I looked through the code step by step and found a solution to my problem.
In the first search, replace id="booksList"
<div class="row" id="booksList">
#Html.Partial("_PartialBooksList")
</div>
partial view in which there was only without id = booksLists.
In the next search there was no ID in this place and there was nothing to replace.
What I am trying to do is have a modal form which contains a file input along with various other form fields, then, once the modal form is submitted, the file input, as well as other form elements, are then moved to the main form I want to eventually submit and I then reset the form and replace the original file input with a clone of the original in order to accept further entries.
Everything works perfectly fine except that the html 5 image preview doesn't work on any cloned file inputs, so it only works on the original file input that's present on page load and not any subsequent inputs.
I've tried changing the event handler as well as recalling handleImages once the clone is added to the DOM but neither seemed to make a difference and I can't think of what to try next.
I've made a codpen and the code is also below:
HTML
<div class="container">
<form action="" class="form-inline" id="image-form">
<label class="btn btn-info upload-button">
Tap to Select Images
<input type="file" style="display: none" multiple accept="image/*" capture="camera">
</label>
<button type="button" class="btn btn-primary" id="save-image">Save Images</button>
<div class="preview">
<div class="row">
</div>
</div>
</form>
<div id="saved-images" style="display: none;"></div>
</div>
JS
var imageCount = 0;
var ImageUpload = function() {
var handleImages = function() {
document.querySelector('#image-form input[type="file"]').addEventListener('change', handleFileSelect, false);
// also tried
// $(document).on('change', '#image-form input[type="file"]', handleFileSelect);
}
var handleFileSelect = function(e) {
if ( !e.target.files || !window.FileReader) return;
var $element = $(e.srcElement).closest('form').find('.preview > .row');
$element.empty();
var $srcElement = $(e.srcElement);
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if (!f.type.match("image.*")) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var html = `
<div class="col-lg-3 col-md-4 col-xs-6 thumbnail m-t m-b m-r m-l">
<img class="img-responsive" src="${e.target.result}" alt="${f.name}">
<div class="title bg-success">${f.name}</div>
</div>
`;
$element.append(html);
}
reader.readAsDataURL(f);
});
}
var handleSaveImage = function() {
$(document).on('click', '#save-image', function(f) {
// Clone the "real" input element
var $real = $('#image-form input[type="file"]');
var $clone = $real.clone(true);
/* Also tried:
var $clone = $real.clone(false);
handleImages();
and
var $clone = $real.clone(true).val('');
*/
// Put the cloned element directly after the real element
$clone.insertAfter($real);
// change the name and class of the real input
$real.addClass(`image-${imageCount}`);
// Move the real element
$real.appendTo('#saved-images');
imageCount++;
resetImageForm();
});
}
var resetImageForm = function() {
$('#image-form').trigger('reset');
$('#image-form .preview').empty();
}
return {
// main function to initiate the module
init: function() {
handleImages();
handleSaveImage();
}
};
}();
jQuery(document).ready(function() {
ImageUpload.init();
});
If I change the event listener to $(document).on('change', '#image-form input[type="file"]', handleFileSelect); then the preview code is reached every time but there's no preview, here's a forked version to show what I mean enter link description here
I seen your code and here is solution
jsfiddle
use $(e.target) instead of $(e.srcElement)
I'm pretty new to html, razor, and MVC so I apologize if this is a easy fix, but I've worked on this issue for a while with no resolution. I would like a controller action to be triggered that re-populates a partial view every time a drop down list changes. I've tried implementing this with the 'onchange' html attribute as well as by setting an id for the drop down and having a jquery function trigger it. But I can't get any of the three functions below to fire. Here's my code..
#model AislesOnlineDataControl.Models.PickupPointsListModel
#{
ViewBag.Title = "PickupPointsList";
}
<script>
function Select() {
#Html.Action("PickupPartial", "PickUpPoint", new { mod = Model.points[Model.selectedID] });
};
$("#PupDropDown").on('change', function () {
#Html.Action("PickupPartial", "PickUpPoint", new { mod = Model.points[Model.selectedID] });
});
$(function() {
$('#PupDropDown').change(function () {
Model.selectedID = Convert.ToInt32(selectPoint.SelectedValue);
//window.location.reload();
#Html.Action("PickupPartial", "PickUpPoint", new { mod = Model.points[Model.selectedID] });
});
});
</script>
<h2>Manage Pick-Up Points</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#{SelectList selectPoint = new SelectList(Model.selectedPoint, "Value", "Text");}
<div class="form-inline">
<div class="row">
#Html.DropDownListFor(model => model.selectedID, selectPoint, null, new { #id="PupDropDown", #onchange = "Select()" })
#Html.ActionLink("New", "CreatePickup", "PickUpPoint", null, new { #class = "btn btn-default pull-right" })
</div>
</div>
<div>
#Html.Partial("~/Views/PickUpPoint/PickupPartial.cshtml", Model.points[Model.selectedID])
</div>
</div>
}
#Html.Action(..) returns the ActionResultfrom your partial view, which eventually turns out to be a block of html code. So you cant put your html code in your JavaScript block.
What you need is the JavaScript code to have a ajax call to the action and render action Result.
Here is example of making simple ajax call in asp.Net MVC
https://stackoverflow.com/a/16186212/2802809
I'm trying to change value of div when data attr of another div will change. I'm trying to do that
$('.language-rate').attr("data-rate-value").on('change', function () {
$('.language-d').text($('.language-rate').attr("data-rate-value"));
});
but it logs in console:
Uncaught TypeError: Cannot read property 'on' of undefined
How can I do that?
my view is:
#using (Ajax.BeginForm("LanguagesTable", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "languages"
}))
{
<div class="language-content">
#Html.TextBoxFor(m => m.newLanguages.LanguageName, new { #class = "pcontent-left main-color" })
<div class="rate language-rate"></div>
#Html.HiddenFor(m => m.newLanguages.Star, new { #class = "language-d" })
</div>
<div class="add-education">
<button type="submit" name="pcprograms" value="add" class="add-education-button-sm">add</button>
</div>
}
I'm using rater js and when star rate changes i want to detect and pass in my model (which is hidden form controll)
EDITED
I'm doing that:
$('.language-rate').on('change', function () {
$('.language-d').text($('.language-rate').attr("data-rate-value"));
});
but it works after second click on div. because i want to detect attribute change event
Unfortunately you cannot hook an event onto a data attribute.There are a lot of posts about this on SO and other sources.What you can do is create a function which runs often (e.g. every 200 milliseconds) and checks if the the value of the data attribute of your div has changed.Here's an example, i hope it helps you:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var _old = $("#test").attr('data-value');
setInterval(function () {
var _new = $("#test").attr('data-value');
if(_old != _new)
{
alert('The data attribute of the div has been changed to - ' + _new);
_old = _new;
}
}, 200);
$("#changeData").click(function () {
$("#test").attr('data-value',new Date().toLocaleTimeString());
});
});
</script>
<div id="test" data-value="Test">
</div>
<input type="button" id="changeData" value="Change Data Attribute" />
I want to redirect the user to a url in a javascript function.
editClick: function () {
var myid = 1;
location.href = '<%= Url.Action("ActionName", "ControllerName", new { id = myid})%>';
};
But 'myId' does not exist in the current context. How do I use a js variable in Url.Action?
An approach that I've taken in the past is to generate the link in the view like so:
<div class='clickmaster'>
<div class='clicker' id='#Url.Action("ActionName", "ControllerName", new { id = Model.Id })'>
Show Something Here
</div>
<div class='clicker' id='#Url.Action("ActionName", "ControllerName", new { id = Model.Id })'>
Show Something Here
</div>
</div>
Then in the javascript I defined a function like this:
$(function() {
$('.clickmaster').on('click', '.clicker' , function() { location.href = this.id; })
});