Display part of html conditionally, does not work - javascript

My page has 2 main parts:
1: part one is shown with form load.
2: part two is shown using ajax call based on clicking the button in part 1.
In part two, I have 3 subparts:
2-1: first is info.
2-2: second is a checkbox.
2-3: third is as a form for create a request (contains input text boxes).
2-2 will be shown if an int parameter is less or equal to zero.
2-3 will be shown if the parameter is bigger than zero, or the checkbox above is checked.
But it doesn't work.
UPDATE: The conditions has no affects on the useNextPeriodConfirm and the request div. Their display is none as initial time.
[HttpGet]
public ActionResult Create()
{
return View();
}
The view:
....
<script>
var id;
$(function() {
$("#getCipContent").click(function() {
loadCipContent();
});
});
function loadCipContent() {
$.ajax({
url: ........../GetFilledContent/' + id,
type: 'get',
success: function(data) {
$("#cipContent").html(data);
}
});
};
</script>
The action method for ajax call:
[HttpGet]
public ActionResult GetFilledContent(string id)
{
.......
ViewBag.Requests = Requests;
if (Requests[0].RemaindQuota <= 0)
{
ViewBag.FromNextPeroidQuota = true;
}
return PartialView("_GetFilledContent", myModel);
}
And the partial view:
#model MyModel
<div>
PAERT 2-1
</div>
<div id="useNextPeriodConfirm" class="row" style="display: none">
#Html.CheckBox("useNextPeriod", false, new { style = "display: inline-block", onchange ="useNextPeriod(this);" })
<label style="display: inline">I am agree</label>
</div>
<div id="request" style="display: none;">
</div>
<script>
window.setTimeout(function() {
if (#ViewBag.FromNextPeroidQuota === true) {
$("#request").hide();
$("#useNextPeriodConfirm").show();
} else {
$("#useNextPeriodConfirm").hide();
$("#request").show();
};
}, 100);
function useNextPeriod(item) {
if (item.checked) {
$("#request").show();
} else {
$("#request").hide();
}
}
</script>

Related

Can't obtain values from controls through javascript in razor page

I have a razor page where evrything is displaying fine, but I need to be able to read the values inside a few controllers to pass them as parameters in an call to prefilter some data:
#page
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#model MyApp.Pages.IndexModel
#{
ViewData["Title"] = "MyApp";
}
<div class="col-12 border p-3 mt-3">
<h3>Filters</h3>
<div class="col-12">
<select id="portMultiselect" name="lsPorts" asp-items="#Model.Ports" multiple></select>
<input id="searchString" type="text" name="searchString">
</div>
</div>
#* A "REFRESHABLE" TABLE GOES HERE...*#
#section scripts{
#* REFRESH SCRIPT *#
<script type="text/javascript">
$(function () {
setInterval(loadTable, 60000);
loadTable();
});
function loadTable() {
var select1 = document.getElementById("portMultiselect");
var selectedPorts = [];
for (var i = 0; i < select1.options.length; i++) {
if (select1.options[i].selected) selectedPorts.push(select1.options[i].value);
}
var searchString = document.getElementById('searchString').value;
if (searchString != "" || selectedPorts.length != 0) {
debugger;
}
fetch('/Index?handler=IndexPartial', {
data: {
searchString: searchString,
selectedPorts: selectedPorts
}
})
.then((response) => {
return response.text();
})
.then((result) => {
document.getElementById('refreshable').innerHTML = result;
});
}
</script>
}
As you can see, I'm trying to capture the selected values in my multiselect and in a text input to pass as parameters in the refresh script.
I'm correctly arriving to the expected endpoint, but Im never getting any values (It's always empty and zero) I even added a debugger in the Javascript code that I'm never hitting.
Why can't I read those values?
EDIT:
I have seen other ways of dealing with these, such as databindings, but as mentioned here, the only way to avoid page reload is javascript and AJAX, so I still need to get these values from the javascript.
At the end, I found a solution to my predicament as follows:
I changed the way I render the selectPicker, following the examples shown in this page:
#page
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#model MyApp.Pages.IndexModel
#{
ViewData["Title"] = "MyApp";
}
<div class="col-12 border p-3 mt-3">
<h3>Filtros</h3>
<div class="row">
<div class="col-6">
<p>Puertos</p>
#Html.DropDownListFor(x =>
x.selectPort,
(IEnumerable<SelectListItem>)ViewData["MyPorts"],
new
{
#id = "portMultiselect",
#class = "form-control selectpicker",
#Value = #Model.Ports,
data_live_search = "true",
multiple = "multiple"
})
</div>
<div class="col-6">
<p>Nombre de variable</p>
<input id="searchString" type="text" name="searchString">
</div>
</div>
</div>
This comes with certain changes to the model you're working with, you can follow instructions to bind data as T.Trassoudaine commmented, here
for this to work you need to add the specified references in your _Layout (for the bootstrap-select), you can check all the things you need to add here
And finally, you will need to work with AJAX in javascript to pass the parameters back:
<script type="text/javascript">
$(function () {
setInterval(loadTable, 1000);
loadTable();
});
function loadTable() {
var select1 = document.getElementById("portMultiselect");
var selectedPorts = [];
for (var i = 0; i < select1.options.length; i++) {
if (select1.options[i].selected) selectedPorts.push(select1.options[i].value);
}
var searchString = document.getElementById('searchString').value.toUpperCase();
var searchPorts = "";
if (selectedPorts.length != 0) {
searchPorts = selectedPorts.join(",");
}
$.ajax({
url: '/?handler=IndexPartial',
data: {
searchString: searchString,
searchPorts: searchPorts
},
success: function (data) {
document.getElementById('refreshable').innerHTML = data;
}
})
}
</script>

send multiple checkbox vales to controller using ajax in asp.net mvc

i have download the Microsoft Music-Store application so i am making some changes in that so what i am changing is that Album model consisting of (id, title, genreId, artistid......) so i want to display list of Album based on genreid using Checkboxes whatever the checkboxes i clicked the list should be displayed so i written the code like this.
here i have small problem what that means when i go to GenericList view where all genre name are displaying(showing in every genre name with checkbox this checkboxes are unchecked) but list of album is not showing (where all checkboxes are unchecked list should be displayed) when every i checked some checkboxes it displaying exactly but unchecked all checkboxes list of album are not showing.so please help me what changes i have to make
Controller:
`public ActionResult GenericList()
{
ViewBag.Generic = db.Genres.ToList();
return View();
}`
public ActionResult _GenreList(string cbk)
{
var listIds = new List<Int32>(Array.ConvertAll(cbk.Split(','), Convert.ToInt32));
var list = from a in db.Albums
select a;
if (cbk != null)
{
list = from l in db.Albums
where listIds.Contains(l.GenreId)
select l;
}
else
{
list= from a in db.Albums
select a;
}
return PartialView(list);
}
ActionResult
<ul id="checkboxFilter">
#foreach(var item in ViewBag.Generic)
{
<li>
<div class="custom-checkbox">
<input type="checkbox" class="cbk" id="#item.GenreId.ToString()" /> #item.Name
</div>
</li>
}
</ul>
Javascript
<script>
$(document).ready(function () {
$('.cbk').change(function () {
var ID = "";
$('.cbk').each(function (index, val) {
if ($(this).is(':checked')) {
ID += $(val).attr("Id") + ",";
alert('id Name: ' + ID);
}
});
var data = {};
data.cbk = ID.slice(0, ID.length - 1);
if (ID != 0) {
$.ajax({
url: '/Home/_GenreList',
method: 'POST',
data: data,
success: function (data) {
$("#Generic_list").html(data);
},
error: function () {
alert("Something went Worng.");
}
});
}
});
});
You need to set the same name for all the checkboxes in the group e.g. "name"="genres"
and value attribute to the value you want to pass to the controller e.g. "value="#item.GenreId.ToString()".
Then in the controller, you'll receive a genre array e.g.
public ActionResult _GenreList(string[] genres)

ASP.NET MVC -Refresh CodeMirror editor onclick

I have a codemirror editor in a partial view and a list of files in the main view. I want to refresh the editor once a file name is clicked. I tried many solutions provided on StackOverflow and other websites but nothing worked , and This is my first time using Javascript so I can't figure out What am I doing wrong.
This is my code:
Controller:
public ActionResult Index()
{
StudentsCodes model = new StudentsCodes();
model.Student = (Student)CurrentUser;
var user = UserManager.FindById(((Student)CurrentUser).InstructorID);
model.Instructor =(Instructor) user;
return View(model);
}
public PartialViewResult DevelopmentPartial (StudentsCodes path )
{
return PartialView(path);
}
Main view:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.js"></script>
<ul id="tree">
#foreach (var file in Directory.GetFiles(Server.MapPath("~/Content/" + Model.Student.UserName + "/CompilerProject/" + name)))
{
var filename = Path.GetFileName(file);
<li id="filelist" onclick="#(Model.path = "~/Content/" + Model.Student.UserName + "/CompilerProject/src/" + #filename)">
<span class="glyphicon glyphicon-file"></span>
#filename
/li>
}
<div id="partial">
#{
Html.RenderPartial("DevelopmentPartial",null);
}
</div>
<script>
$(document).ready(function () {
$("#filelist").click(function (e) {
#{Html.RenderAction("DevelopmentPartial", Model);
}
});
});
</script>
partial view:
#using (Html.BeginForm())
{
var fileContents= "";
if (Model==null)
{
fileContents = "";
}
else
{
fileContents = System.IO.File.ReadAllText(Server.MapPath(Model.path));
}
#Html.TextArea("code", fileContents, new { id = "code" })
}
I can't assign ids for list elements since their number is unknown at compile time and it changes when the user adds or deletes a file, that's why most of the solutions provided didn't work . The result here was 3 editors overlapping and display the contents of the last file. And <li> items are non-clickable. What am I doing wrong in my code ?
Edit:
After updating the script as the following:
<script>
$(document).ready(function() {
$(".filelist").on("click",function (e) {
$("#partial").load('DevelopmentPartial');
});
});
</script>
It refreshes the partial view but the editor is always empty, and the Model is always null. Is it wrong to update the Model using "onclick"?
In case someone faced the same problem, I solved it by changing id to class at the list, then by using this script:
<div id="partial">
#{
Html.RenderAction("DevelopmentPartial", new { path1 = Model.path});
}
</div>
<script>
$(document).ready(function () {
$('.filelist').on('click', function (e) {
alert('Im clicked on filePath = ' + $(this).attr('value'));
var filePath = $(this).attr('value'); //value is attribute set in Html
$('#partial').load('DevelopmentPartial', { path1: filePath });
});
});
</script>
And the controller:
public PartialViewResult DevelopmentPartial(string path1)
{
modelSC.path = path1;
return PartialView(modelSC);
}
where modelSC is a global variable in the controller.

MVC 5, Ajax, Jquery - script works only once

<script>
$(function () {
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-form").submit(ajaxSubmit);
});
</script>
Ok, This script is for searching some content from databse. it works great, but only once. When im trying to hit submit again in my from, its not working again. Only when I refresh page.
Could someone help me?
My from in same index.cshtml file:
<div>
<form id="search-form" method="get" data-ajax="true" data-ajax-target="#zawartosc" data-ajax-update="#zawartosc">
<input id="search-filter" type="search" name="searchQuery"
data-autocomplete-source="#Url.Action("MiejscaPodpowiedzi", "Miejsce")"
placeholder="Wprowadź tekst, aby filtrować..." />
<input type="submit" id="send" value="Send" />
</form>
<div id="zawartosc">
#Html.Partial("_ListaMiejsc")
</div>
My controller:
public class HomeController : Controller
{
private DaneKontekst db = new DaneKontekst();
public ActionResult Index(string searchQuery = null)
{
var miejscaNaSwiecie = db.MiejscaNaSwiecie.Where(o => (searchQuery == null ||
o.NazwaMiejscaNaSwiecie.ToLower().Contains(searchQuery.ToLower()) ||
o.KrajMiejscaNaSwiecie.ToLower().Contains(searchQuery.ToLower()) ||
o.OpisMiejscaNaSwiecie.ToLower().Contains(searchQuery.ToLower()))).ToList();
var ViewModel = new HomeIndexViewModel()
{
MiejscaNaSwiecie = miejscaNaSwiecie
};
if (Request.IsAjaxRequest())
{
return PartialView("_ListaMiejsc", ViewModel);
}
return View(ViewModel);
}
Edited.
Because you are replacing the container. You should update only the content of that.
When you click for the first time, the response of the ajax call (the markup for the form) will replace the div (with id ="zawartosc"). So after this you do not have that div exist in your DOM any more. So your $targetElement is not going be the the container div (because it is gone !)
So instead of replacing the container div, simply update the content of that.
Replace
$($targetElement).replaceWith($newContent);
with
$($targetElement).html($newContent);
$($targetElement).html($newContent);
OR
$($targetElement).Load($newContent);

BeginCollectionItem new element not working with jQuery MVC 5

I'm trying to test whether content is in a text field, this works with initially loaded elements, but not the elements (which share the same class name) added using beginCollectionItem.
For example a textbox is added through bci and gets filled in, when filled in and focus goes elsewhere, the textbox will be given the 'makeitred' class.
What's wrong with the javascript I'm using?
partial using BCI
<div class="editorRow">
#using (Html.BeginCollectionItem("ispDetails"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.type, new { #class = "isitempty" })
</span>
</div>
</div>
}
</div>
Index segment calling partial - on page load elements the jQuery works, anything there after using the add button doesn't
#using (Html.BeginForm())
{
<div id="editorRowsEQM">
#foreach (var item in Model.ispDetails)
{
#Html.Partial("EquipView", item)
}
</div>
#Html.ActionLink("Add", "ispManager", null, new { id = "addItemEQM", #class = "button" });
}
JS from the Index
$(function () {
$('#addItemEQM').on('click', function () {
$.ajax({
url: '#Url.Action("ispManager")',
cache: false,
success: function (html) { $("#editorRowsEQM").append(html); }
});
return false;
});
$(document).on('change', '.isitempty', function checkFill (e) {
if ($(this).val().length == 0) {
$(this).removeClass('makeitred');
} else $(this).addClass('makeitred');
});
});

Categories

Resources