BeginCollectionItem Maintain Page Position MVC 5 - javascript

I'm trying to find the best method (any at this point) in which to keep page scroll position when deleting an item from a list using beginCollectionItem.
Initially I thought it was due to my other javascript/jQuery code in my main project (it still could be a factor), but when I recreated the situation in a new project only using the BCI code (index, two partials, controller, and model), when deleting an item from either of the lists, the page would jump to the top again, I really need (want) this to stop, how can I achieve this?
I have seen this question and the top answer I don't know how to properly implement or even if it's still valid, the second answer, using the below JS I have tested within my _Layout, within the budles which didn't fix the issue.
jQuery test
$(document).scroll(function () {
localStorage['page'] = document.URL;
localStorage['scrollTop'] = $(document).scrollTop();
});
$(document).ready(function () {
if (localStorage['page'] == document.URL) {
$(document).scrollTop(localStorage['scrollTop']);
}
});
Student Partial
#model UsefulCode.Models.Person
<div class="editorRow">
#using (Html.BeginCollectionItem("students"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.firstName)
</span>
</div>
<div class="ui-block-b">
<span>
#Html.TextBoxFor(m => m.lastName)
</span>
</div>
<div class="ui-block-c">
<span>
<span class="dltBtn">
X
</span>
</span>
</div>
</div>
}
</div>
Teacher Partial
#model UsefulCode.Models.Person
<div class="editorRow">
#using (Html.BeginCollectionItem("teachers"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.TextBoxFor(m => m.firstName)
</span>
</div>
<div class="ui-block-b">
<span>
#Html.TextBoxFor(m => m.lastName)
</span>
</div>
<div class="ui-block-c">
<span>
<span class="dltBtn">
X
</span>
</span>
</div>
</div>
}
</div>
Index
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model UsefulCode.Models.Register
<div id="studentList">
#using (Html.BeginForm())
{
<div id="editorRowsStudents">
#foreach (var item in Model.students)
{
#Html.Partial("StudentView", item)
}
</div>
#Html.ActionLink("Add", "StudentManager", null, new { id = "addItemStudents", #class = "button" });
}
</div>
<div id="teacherList">
#using (Html.BeginForm())
{
<div id="editorRowsTeachers">
#foreach (var item in Model.teachers)
{
#Html.Partial("TeacherView", item)
}
</div>
#Html.ActionLink("Add", "TeacherManager", null, new { id = "addItemTeachers", #class = "button" });
}
</div>
#section scripts {
<script type="text/javascript">
$(function () {
$('#addItemStudents').on('click', function () {
$.ajax({
url: '#Url.Action("StudentManager")',
cache: false,
success: function (html) { $("#editorRowsStudents").append(html); }
});
return false;
});
$('#editorRowsStudents').on('click', '.deleteRow', function () {
$(this).closest('.editorRow').remove();
});
$('#addItemTeachers').on('click', function () {
$.ajax({
url: '#Url.Action("TeacherManager")',
cache: false,
success: function (html) { $("#editorRowsTeachers").append(html); }
});
return false;
});
$('#editorRowsTeachers').on('click', '.deleteRow', function () {
$(this).closest('.editorRow').remove();
});
});
</script>
}

Aside from inflicting pain to myself for how dense I now feel I am relieved.
Adding return false; to the delete action resolves this, it was present on the add action but from staring at it for hours I just assumed it was there.
If there is a better answer, please put it in as this will only work on this section of code.
Below is the answer code:
$('#addItemStudents').on('click', function () {
$.ajax({
url: '#Url.Action("StudentManager")',
cache: false,
success: function (html) { $("#editorRowsStudents").append(html); }
});
return false;
});
$('#editorRowsStudents').on('click', '.deleteRow', function () {
$(this).closest('.editorRow').remove();
return false; // add this
});

Related

on check checkbox hide/show div in view

I'm trying to show MeetingDiv when IsAnonymous is checked and when IsMeeting is checked, MeetingTextBox should be shown.
Tried .click, .change and live and nothing worked. I don't know where I'm wrong.
<div class="col-md-4 sidePad" >
#Html.Label("Is Anonymous")
#Html.CheckBoxFor(p => p.IsAnonymous, new { id = "CBAnonymous"})
</div>
<div class="col-md-6" id="MeetingDiv" style="display:none">
#Html.Label("Is Meeting")
#Html.CheckBoxFor(p => p.IsMeeting, new { id = "CBMeeting"})
</div>
<div class="col-md-6" id="MeetingTextBox" style="display:none">
#Html.Label("Meeting Name")
#Html.TextBoxFor(p => p.MeetingName, new { id = "TBMeetingName"})
</div>
<script>
$(function () {
$("#CBAnonymous").click(function () {
if ($(this).prop("checked")) {
$("#MeetingDiv").show();
} else {
$("#MeetingDiv").hide();
}
});
});
</script>
Try this
$('#CBAnonymous').change(function(){
if(this.checked)
$("#MeetingDiv").show();
else
$("#MeetingDiv").hide();

Insert Data from Modal Bootstrap MVC 4 + JQuery (Post Method)

I have a modal form that save me on certain data information, work correctly, but I need to update a in my view with the response and doesn't work correctly and bring me a list without format and class css, like when an error occurs, the modal disappears and brings back a page without css with all the validates error, what I have wrong in my code or that I do to fix it?
My Partial View
#model ControlSystemData.Models.Tourist
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel-Update">Ingresar Turista</h4>
</div>
#using(#Html.BeginForm("Create","Tourist", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="modal-body" style="text-align:center; padding:10px;">
#if (!string.IsNullOrWhiteSpace(ViewBag.Error))
{
<div class="alert alert-danger alert-dismissable" id="danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#ViewBag.Error
</div>
}
<div class="panel-body">
<div class="form-group">
#Html.TextBoxFor(u => u.Name, new { #class = "form-control", #placeholder = "Nombre del Pasajero" })
#Html.ValidationMessageFor(u => u.Name)
</div>
#*More Data Here*#
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</fieldset>
}
My Modal Bootstrap
<!--Modal Tourist-->
<div class="modal fade" id="Modal-Tourist" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<p class="body">
</p>
</div>
</div>
</div>
<!--End Modal Tourist-->
My Controller
[HttpPost]
public ActionResult Create(Tourist collection)
{
if (ModelState.IsValid)
{
db.Tourist.Add(collection);
db.SaveChanges();
return RedirectToAction("IndexByEventsTourist", "Tourist", new { id = collection.id });
}
Response.StatusCode = 400;
return PartialView("Create", collection);
}
My Script
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
function clearErrors() {
$('#msgErrorNewTourist').html('');
$('#alert').html('');
}
function writeError(control, msg) {
var err_msg = '<div class="alert-message error"><a class="close" href="#">×</a><p>' + msg + '</p></div>';
$('#' + control).html(err_msg);
}
$(document).ready(function () {
$('#Modal-Tourist form').on('submit', function () {
if ($(this).valid()) {
$.ajax({
url: '#Url.Action("Create","Tourist")',
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
$("#eventsDetailsList").html(result);
},
error: function (err) {
writeError('body', 'Wrong Data');
}
});
}
return false;
});
function getRequest(url) {
jQuery.noConflict();
$.ajax({
url: url,
context: document.body,
success: function (data) {
$('.modal-content p.body').html(data);
$('#Modal-Tourist').modal('show');
$('#Name').focus();
},
error: function (err) {
writeError('msgErrorNewTourist', err.responseText);
}
});
}
$('a.newTourist').click(function () {
var id = $(this).attr("eventsid");
var url = '#Url.Content("~/Tourist/Create")/' + id;
getRequest(url);
return false;
});
});
</script>
I need that the modal stay in your position with your errors or rendering my correctly with the update.
Thanks
Images
RedirectToAction
public ActionResult IndexByEventsTourist(int id)
{
ViewBag.id = id;
var eventsById = db.Events.Where(u => u.id == id).FirstOrDefault();
ViewBag.Events = eventsById;
var touristByEvent = db.Tourist.Where(u => u.id == id).Include(u => u.Events).ToList();
ViewBag.TouristByEvent = touristByEvent;
return PartialView("IndexByEvents", touristByEvent);
}
Parent page (Render Div with the Partial Render or Update from Modal)
<div class="col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-plus"></i> Add
</div>
<div class="panel-body">
<div class="row">
<div id="msgErrorNewTourist"></div>
<div class="col-lg-12" id="eventsDetailsList">
#{Html.RenderAction("IndexByEventsTourist", "Tourist", new { id = Model.id });}
</div>
</div>
</div>
</div>
</div>
</div>
After many tries, I changed the <script></script> (my script it was very obsolete) and I modified the <script> of this answer for my intent of load content dynamically and Validate the form before Post, Many Thanks to Sthepen Muecke for provide me a solution and clarify my issues... Thank you so much.
New Code Script for Load Content Dinamically and Validate Inputs in Modal Bootstrap 3
<script type="text/javascript" src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('a.newTourist').click(function () {
var url = '#Url.Action("Create", "Tourist", new { id = #Model.id })';
$(jQuery.noConflict);
$('#ModalContent').load(url, function (html) {
var form = $("#Modal-Tourist form");
$.validator.unobtrusive.parse(form);
$("#Modal-Tourist").modal('show');
form.submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#Modal-Tourist').modal('hide');
var content = '#Url.Action("IndexByEventsTourist", "Tourist", new { id = #Model.id })';
$('#eventsDetailsList').load(content);
}
});
return false;
});
});
});
});
</script>

Why doesn't my dropdown submit the form?

Here's my code:
<div class="center">
<p> Choose item:</p>
<div class="dropdown">
#using (Html.BeginForm("Start", "Home", FormMethod.Post, new { name = "form", id = "form" }))
{
#Html.DropDownListFor(x => x.SelectedId, #Model.ViewJaren,
new
{
onchange = "this.parentNode.form.submit()"
}
)
}
</div>
</div>
Been trying to get it to work but can't figure it out. I got the onchange to work with document.getElementById("form"). But there is no value passed. I get a blank page.
why not just separate it out.
<script>
$(document).ready(function(){
$('##Html.IdFor(x => x.SelectedId)').change(function(e){
$(this).closest('form').submit();
});
});
</script>

Why my previous button doesn't contain parameter for the controller ? PagedList MVC

i have a problem when implementing pagedlist mvc in my website project. I used pagedlist mvc to show partial view. When button previous is click, the parameter doesn't complete pass, just the page number that pass and the other is null. This is my controller
public ActionResult StoreItemView(string jenis, string sorting_key, int? Page_No)
for previous button it will create link like this
localhost:20208/StoreItem/StoreItemView?Page_No=1
and has different with next button,that create link that contain all parameter
localhost:20208/StoreItem/StoreItemView?jenis=&sorting_key=&Page_No=2
why it's different call for previous and next button ?
i create the pager like this in cshtml
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action(
"StoreItemView",
new
{
jenis = ViewBag.jenis,
sorting_key = ViewBag.sorting_key,
Page_No = page
}
),
PagedListRenderOptions.PageNumbersOnly
)
</div>
and i use javascript too for load partial view , my javascript is
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});
</script>
I stuck in this problem almost 2 days. I hope the people who are here can help me. Thank you before :)
----EDIT------
#model PagedList.IPagedList<MVC_EDOLPUZ.Models.StoreItemModel>
#using System.Globalization
#using PagedList.Mvc
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
<h3><span class="label label-primary">DOLANAN PUZZLE ITEM</span></h3>
<select id="Sorting_Order" name="Sorting" onchange="reloadPartialDDL()">
<option value="0">-Urutkan Berdasarkan-</option>
<option value="nama">Nama</option>
<option value="rendah">Harga Terendah</option>
<option value="tinggi">Harga Tertinggi</option>
</select>
<div id="products" class="row list-group">
#foreach (var item in Model)
{
<div class="item col-xs-5 col-lg-3">
<div class="thumbnail">
<img class="group list-group-image img-responsive" src="#Url.Content(#item.gambar_barang)" alt="" />
<div class="caption">
<h4 class="group inner list-group-item-heading">
#item.nama_barang
</h4>
<p class="group inner list-group-item-text">
<span class="label label-warning">#item.deksripsi_barang</span>
</p>
<div class="row">
<div class="col-xs-1 col-md-6">
<input id="#item.nama_barang" type="number" class="rating" min="1" max="5" step="0.5" data-size="xs" value="#item.rating_barang">
</div>
<script>
$('##item.nama_barang').rating('refresh', { disabled: true, showClear: false, showCaption: false });
</script>
</div>
<div class="row">
<div class="col-lg-5 col-xs-4">
<p class="lead" style="font-weight: bolder; color: red;">
#string.Format(new CultureInfo("id-ID"), "{0:C}", #item.harga_barang)
</p>
</div>
<div class="col-lg-1 col-xs-2">
<a class="btn btn-success btn-responsive btn-xs" onclick="addItemToCart('#item.id_barang')" href="#">Add to cart</a>
</div>
</div>
</div>
</div>
</div>
}
</div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#*#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))*#
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action(
"StoreItemView",
new
{
jenis = ViewBag.jenis,
sorting_key = ViewBag.sorting_key,
Page_No = page
}
),
PagedListRenderOptions.PageNumbersOnly
)
</div>
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});
</script>
that's my code for the view, and this controller that handle it's view
[HttpGet]
public ActionResult StoreItemView(string jenis, string sorting_key, int? Page_No)
{
ViewBag.jenis = jenis;
ViewBag.sorting_key = sorting_key;
List<StoreItemModel> products = StoreItemRepository.getItemList(jenis, sorting_key);
foreach (var items in products)
{
items.rating_barang = StoreItemRepository.getRatingBarang(items.id_barang);
}
int Size_Of_Page = 4;
int No_Of_Page = (Page_No ?? 1);
PagedList.PagedList<StoreItemModel> show = new PagedList.PagedList<StoreItemModel>(products, No_Of_Page, Size_Of_Page);
return PartialView("_StoreItem", show);
}
Please use like below
<div id="myPager" location="Url.Action("StoreItemView", new {jenis = ViewBag.jenis, sorting_key = ViewBag.sorting_key, Page_No = page})">
#Html.PagedListPager(
Model,
page => Url.Action("StoreItemView"),
PagedListRenderOptions.PageNumbersOnly
)
and javascript must be like
Before using the please check ViewBag.sorting_key and ViewBag.jenis is holding any value using alert in javascript. and I am not qable to see any tag with id="container_item_store". Make sure the container_item_store id must be place in some where in your view.
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
var location = $(this).attr('location');
$.ajax({
url: location,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});

Append to class if hidden div value is equal to attribute from XML

I've searched and tried for 2 days now, with no luck whatsoever.
What i'm trying:
I generate several div's through a foreach in xslt, that contains a hidden div where i store a code to match value out of an external xml file on. Something like this:
<div class="pakket_content">
<a href="http://">
<div class="waardering_wrapper col-xs-12">
<div class="sterwaardering col-xs-8">
<img src="http://">
</div>
<div class="CODE">CODE</div>
<div class="waardering col-xs-4">
<p>-</p>
</div>
<div class="waardering pull-right">
<b>-</b>
</div>
</div>
</a>
<a href="">
<button type="button" class="btn btn-default btn-md pull-right col-xs-12">
Nu boeken!
<span class="glyphicon glyphicon-arrow-right"></span>
</button>
</a>
</div>
Where the div class 'code' contains the code to match on.
The xml that comes out of this is:
<entities>
<accommodation cms-id="458245" external-id="CODE" name="Trip A">
<destination cms-id="45541" name="Paramaribo" level="destination"/>
<country cms-id="4545" name="Suriname" level="country"/>
<accommodation-type>Hotel</accommodation-type>
<testimonial-count>88</testimonial-count>
<average-testimonial-score>7.6</average-testimonial-score>
<deep-link>
http://link.com
</deep-link>
<testimonial-count-per-language>88</testimonial-count-per-language>
<testimonial-count-all>88</testimonial-count-all>
<average-testimonial-score-all>7.6</average-testimonial-score-all>
</accommodation>
</entities>
Now i wanted to append the average-testimonial-score to div "waardering" when the external-id attribute in equals the value in . But how would i go about that?
I tried with looping through the value of the div class and the attribute, like this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "file.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('accommodation').each(function(index) {
var cijfer = $(this).find('average-testimonial-score-all').text();
$('.CODE').each(function(index) {
var divcode = $(this).text();
$.attr('external-id').each(function(index) {
var attrcode = $(this).text();
if (divcode == attrcode) {
$(".waardering").append(cijfer);
};
});
});
});
}
});
});
With no result.
Can someone push me in the right direction with this?
Fetching accommodation external-id in correct way (according to how .attr() is supposed to work), the code works as it should.
I omitted Ajax request for testing.
Fiddle.
$(document).ready(function()
{
var xml = '<entities><accommodation cms-id="458245" external-id="CODE" name="Trip A"> <destination cms-id="45541" name="Paramaribo" level="destination"/> <country cms-id="4545" name="Suriname" level="country"/> <accommodation-type>Hotel</accommodation-type> <testimonial-count>88</testimonial-count> <average-testimonial-score>7.6</average-testimonial-score> <deep-link>http://link.com</deep-link> <testimonial-count-per-language>88</testimonial-count-per-language> <testimonial-count-all>88</testimonial-count-all> <average-testimonial-score-all>7.6</average-testimonial-score-all> </accommodation></entities>';
$(xml).find('accommodation').each(function(index)
{
var cijfer = $(this).find('average-testimonial-score-all').text();
var externalId = $(this).attr("external-id");
$('.CODE').each(function(index)
{
var divcode = $(this).text();
if (divcode == externalId)
{
$(".waardering").append(cijfer);
};
});
});
});

Categories