How do I get the values of a BeginCollectionItem in javascript - javascript

I want to get values of a BeginCollectionItem using javascript but it seems like i am not winning
my html
#using HtmlHelpers.BeginCollectionItemCore
#using E_Commerce.Application.Models
#model ProductImageModel
<li class="mb-2">
#using (Html.BeginCollectionItem("ProductImages"))
{
Html.RenderPartial("_imagesPartial", Model);
}
</li>
the _imagesPartial html
#model E_Commerce.Application.Models.ProductImageModel
<div class="col-md-12 row mb-2">
<div class="col-md-4 imageDiv">
<img class="border rounded" />
</div>
<div class="col-md-4">
<input type="file" asp-for="File" onchange="uploadImageTest(this)" />
</div>
<div class="col-md-4">
Remove
</div>
</div>
and my javascript
let addNewImagesFormSubmit = (event) => {
var Id = $("#Id").val();
var productImages = $("#ProductImages").val();
$.ajax({
url: "#Url.Action("AddNewImages","ProductImage")",
data: {
Id: Id,
productImages:productImages
},
success: function (data) {
$("#productImagesDiv").html(data);
}
})
}
the server side does not seem to get any images when using javascript to get the BeginCollectionItem.
how do i get it to work

Related

Use JsonResponse variable from Django in Html via ajax

I am returning JsonResponse with the required hash from Django view on a ajax call.
How to use the Json object inside html via {{}} (jinja templating). Below is my ajax call:
$(function () {
$('#getData').submit(function (e) {
e.preventDefault();
$.ajax({
url: "/Report",
type: 'get',
data: {
'date1': $('#d1').val(),
'date2': $('#d2').val(),
},
success: function (data) {
alert("Success");
// How to pass the data here to use it in html
}
});
});
});
My sample html :
<div id="maindiv" class="col col-5 col-sm-10" style="display: none;">
<div>
<h3> Showing Results for {{info.fromDate}} to {{info.toDate}}</h3>
</div>
<br><br>
<div id="summary">
<div class="card-deck">
<div class="card mx-auto">
<div class="card-body text-center">
<p style="text-align: center;vertical-align: middle;padding: 20px;" class="card-text">
<h1><b><span style="font-size:80px;">{{info.total}}</span></b></h1>
<h6> Total </h6>
</p>
</div>
</div>
<div class="card" id='chart1' style="width: 100%; height: 500px;">
<div class="card-body text-center">
<script>
Info = {{ info.marks| safe }}
createpiechart("marks", 'chart1', Info); <!-- This creates an amchart -->
</script>
</div>
</div>
</div>
</div>
This is just a sample. I have many more charts and processing for which I used the jsonresponse variable via {{}} inside html. What is the correct way to get the data from ajax to html?
Initially I used render to return response to html. But I see that the data I capture in ajax has the entire html replaced with the {{}} variable's value
return render(request=request, template_name='home/home.html', context={"info": InfoArray})
How to use the hash/context I pass from Django view inside html via a ajax ?
App\home.urls file:
urlpatterns = [
#path('', views.index, name = "index"),
path('', views.homepage, name="homepage"),
]
App\urls file:
urlpatterns = [
path('Report/', include('home.urls')),
path('admin/', admin.site.urls),
]

res.render() function rendering an ejs page doesn't refresh the UI, but the ejs page get called

I have a list of resources which needs to be filtered based on the location. I have a form to filter and on click of a button, the data is filtered based on the location. I have an AJAX request and it sends a post request to /filterresources and the data matching that criteria is also fetched from the db and the resourcefilter.ejs is rendered using res.render() as given below:
resourcefilter.js:
router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
db.findAll(Resource,{category:category})
.then(function(data){
res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});
});
The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.
resourcefilter.ejs: All console statements in this get printed without any issues but UI is not refreshed. Any help is much appreciated.
<% layout('layout/layout') %>
<div class="container user-form py-5">
<br>
<%if(user.role == 'Administrator'){ console.log(user.role);%>
<a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
<%}%>
</br>
<span class="site-logo my-3">Our Resources</span>
<div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
<form id="filter-resources" class="mt-5">
<div>
<select class="custom-select" name="category" id="category">
<option selected>Select a location:</option>
<option value="Pittsburgh">Pittsburgh</option>
<option value="Allegheny County">Allegheny County</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Outside Pennsylvania">Outside Pennsylvania</option>
</select>
<input class="filter" name="filter-resources" type="submit" value="Filter">
</div>
</form>
</div>
</form>
<div class="container" style="margin-top: 2%;">
<div class="row">
<% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="image-flip" ontouchstart="this.classList.toggle('hover');">
<div class="mainflip">
<div class="frontside">
<div class="card-custom">
<% console.log("Image"+resources[i].image);%>
<div class="card-body text-center">
<img src="<%= resources[i].image %>" alt="" class="img-resources">
<div class="card-title"><b><%= resources[i].name%></b></div>
<div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
<a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
Read More!</a>
<br></br> </div>
</div>
<br></br>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
AJAX function to call to /filterresources:
function filter_resources(e) {
e.preventDefault();
var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];
//Form Handling with ajax
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
});
function refreshDiv() {
document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
}
}
Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.
If you don't have any errors from your server you can do a workaround with the front end:
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
}).then(() => location.reload());
That will refresh your page when the request finishes.
location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:
filterresources.js
router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
var user = req.user._id;
console.log(user);
db.findAll(Resource,{category:category})
.then(function(data){
res.send({msg: data, success: true,user: user });
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});
});
AJAX function:
function filter_resources(e) {
e.preventDefault();
var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];
//Form Handling with ajax
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
success: function (response) {
if (!response.success) {
window.alert(response.msg);
}
if (response.success) {
var resource = response.msg;
var userInfo = response.user;
$('#resfilter').html(""); // reset the contents in the div
var html = `<div class="row">`;
for(var i=0;i<resource.length;i++) {
html += `<div class="col-xs-12 col-sm-6 col-md-4">
<div class="image-flip" ontouchstart="this.classList.toggle('hover');">
<div class="mainflip"> <div class="frontside"> <div class="card-custom">
<div class="card-body text-center">`;
html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
html += ``;
html += `Read More!`;
html += `<br>`;
html += `</br></div></div><br></br></div></div></div></div>`;
}
html += `</div></div></div></div>`;
}
document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
}
})
}

Bind Multi Line HTML content from JQuery Ajax response

This is the part of my html code that binds to the view using a Model object.
#if (Model.Comments != null)
{
#foreach (var thread in Model.Comments.Threads)
{
<div class="comment-wrap">
<div class="comment-head">
<div class="subsciber-user" style="background: #DDEFC5">#thread.UserName.Substring(0, 2).ToUpper()</div> #thread.UserName <span>#thread.PostedDate.ToString("dd MMM yyyy")</span>
<div class="edit-comment"><img class="comment-edit-img" src="~/images/edit-task.svg"></div>
</div>
<div class="clearfix"></div>
<div class="comment-content">
#thread.Content
</div>
#if (thread.Attachment != null)
{
<div class="comment-attachment">
<div class="ca-head">#thread.Attachment.Count() Attachments<i><img class="c-download" src="~/images/download.svg" alt="" /></i></div>
<div class="ca-tiles">
#foreach (var item in thread.Attachment)
{
<span><img src="#item.AttachmentUrl" alt="Smiley face"></span>
}
</div>
</div>
}
</div>
}
}
My requirement is I want to bind this HTML from a jquery Ajax Success. for that, I created an Ajax call.
var val1 = $('#TaskId').val();
#*$(document).ready(function () {
$.ajax({
url: '/Task/GetTaskComments',
data: { id: val1},
dataType: "json",
success: function (comments) {
// here i neeed to bind this Html block using each loop,
// here we are getting the same response that we are getting Model.Comments in the above code as json
}
});
});
I want to append the looped Html content from ajax success inside my
<div class="bindComments">
</div>

show records on same details page by clicking next button in asp.net mvc getting error

I want to display the records on details page when user click on next button then he should be able to display the next record of table. Suppose user select the details of a particular record id 1 he get the details of that id 1 at the same time on the same page by clicking the next button user should be able to get the record of id 2 and vice versa. I have done it but getting some error when table has no such id named id 3 after id 1 and id 2 its showing me the error. Please help me to find out where i am wrong.
View
#model WebApp.ViewModels.ViewTeamList
<script type="text/javascript">
var dataid = '#Html.Raw(Json.Encode(Model.TeamDetails.TeamId))';
for( var item in dataid)
console.log(dataid[item]);}();
</script>
<script type="text/javascript">
$("#btnNext").click(function () {
var $buttonClicked = $(this);
var nid = $buttonClicked.attr('data-id');
console.log(nid);
$.ajax({
url: 'Team/Next',
data: { dataid: nid },
//data: JSON.stringify(data.TeamId),
success: function (response) {
divDetail.html(data);
}
});
});
</script>
<div class="row">
<div class="col-md-11 col-sm-11 pull-left" style=" font-size:large; font-weight:600">
#Model.TeamDetails.TeamName
</div>
#* <div class="col-md-1 col-sm-1 pull-right">*#
<div class="navi-but">
<a href="#" id="btnPrevious" data-id="#Model.TeamDetails.TeamId" class="details">
<span class="previous">Previous</span>
</a>
<a href="#" class="details" data-id="#Model.TeamDetails.TeamId" id="btnNext">
<span style="padding-right:7px">Next</span><span class="next"></span>
</a>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="~/Images/settings.png" />
</a>
<ul class="dropdown-menu" role="menu">
<li>Edit</li>
</ul>
</li>
</div>
#* </div>*#
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblTeam","CT Team Name:")
</div>
<div class="col-md-8 col-sm-8">
#Model.TeamDetails.TeamName
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblDescription","Description:")
</div>
<div class="col-md-8 col-sm-8">
#Model.TeamDetails.Description
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblCTUserCount","User Count")
</div>
<div class="col-md-8 col-sm-8 pull-left">
#Model.TeamDetails.UserCount
</div>
</div>
Controller
public ActionResult Next(int dataid)
{
dataid++;
ViewTeamList viewTeamList = new ViewTeamList();
viewTeamList.ViewTeamDetails(dataid);
return PartialView("_ViewTeamDetails", viewTeamList);
}
View model
public class ViewTeamList
{
public TeamDetails TeamDetails;
private ITeamService teamService;
public ViewTeamList()
{
}
public void ViewTeamDetails(int Id)
{
teamService = new TeamService(pDbContext);
TeamDetails = teamService.GetTeamDetails(Id);
//return (TeamDetails.First());
}
}
Please help where i am doing wrong.
I didn't look your code in detail but it seems to me that you have a logical problem. Since you are always incrementing id by one ( dataid++; ) that won't work if some record is deleted in the meantime. For example let's say that you have Record1 with id 1, Record2 with id 2 and Record 3 with id 3 and you delete Record2. Now when you are trying to get next record after Record1 you are incrementing id by 1 so you have 2 and there is no record with id 2 in the db anymore.
Instead of dataid++; you should find next id that really exists in db. As I said I didn't read code in detail so there may be more possible problems.
To Display from WebMethod You Should follow these steps:
create
[webmethod]
to retrieve all the data
List items then make a javascript method in client side use:
ajax({ type:'post', url:'exaple.aspx/showMethod', data:{}, datatype:'json', contentType:'application/json; charset=utf-8',
scuccess:function(data) --display from here in table or any other
data ), error:function(){ alert('Error'); } })

Infinity Ajax Request When Drop Change in Knockout MVC

I am using Knockout MVC in my project. I try to pass the viewModel to when Drop Down changing . but when I try this method call several times and the alert "ok" invoke continuesley. Can any one please help me on this??
$(function () {
$('#rmch').change(function () {
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
alert("Ok");
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
});
My Json Method
public JsonResult DropChange(HotelModel hotelmod)
{
//hmodel.RoomModel = new List<RoomModel>();
//for (int i = 1; i <= hmodel.NoOfRooms; i++)
//{
// hmodel.RoomModel.Add(new RoomModel { adultsDrp = ListItems.GetList(1, 6), childDrop = ListItems.GetList(0, 5) });
// //hmodel.RoomModel.Add(new RoomModel { });
//}
var jjj = JsonConvert.SerializeObject(hotelmod);
return Json(hotelmod);
}
My View
<div class="search-tab-content">
<div class="tab-pane fade active in" id="hotels-tab">
<form id="searchfrm">
<div class="title-container">
<h2 class="search-title">Search and Book Hotels</h2>
<p>We're bringing you a new level of comfort.</p>
<i class="soap-icon-hotel"></i>
</div>
<div class="search-content">
<h5 class="title">Where</h5>
<label>Your Destination</label>
#ko.Html.TextBox(m => m.Destination, new { #class = "input-text full-width", #placeholder = "Any destination, country, city code" })
#ko.Html.Hidden(new { #Id = "DesCode" }).Value(m => m.DesCode)
<hr>
<h5 class="title">When</h5>
<div class="row">
<div class="col-xs-4">
<label>Check In</label>
<div class="datepicker-wrap">
#ko.Html.TextBox(m => m.CheckInDate, new { #class = "input-text full-width" })
</div>
</div>
<div class="col-xs-4">
<label>Check Out</label>
<div class="datepicker-wrap">
#ko.Html.TextBox(m => m.CheckOutDate, new { #class = "input-text full-width" })
</div>
</div>
<div class="col-xs-4">
<label>ROOMS</label>
<div class="selector">
#ko.Html.DropDownList(m => m.RoomList, new { #class = "full-width jkl", #id = "rmch" }, "Text", "Value").Value(m => m.NoOfRooms)
</div>
</div>
</div>
<hr>
<div id="p_scentsFH">
#using (var rmModel = ko.Foreach(m => m.RoomModel))
{
<h5 class="title">Room 1</h5><div class="row">
<div class="col-xs-3">
<label>ADULTS</label>
<div class="selectorgen">
#rmModel.Html.DropDownList(m => m.adultsDrp, new { #class = "full-width" },"Text","Value").Value(m=>m.adultscount)
</div>
</div>
<div class="col-xs-3">
<label>KIDS</label>
<div class="selectorgen">
#rmModel.Html.DropDownList(m => m.childDrop, new { #class = "full-width" }, "Text", "Value").Value(m => m.childcount)
</div>
</div>
<div class="agecls">
#using(var chage=rmModel.Foreach(m=>m.childage))
{
<div class="col-xs-3">
<label>Child</label>
<div class="selectorgen">
#chage.Html.DropDownList(m => m.ageDrop, new { #class = "full-width" },"Text","Value").Value(m=>m.Age)
</div>
</div>
}
</div>
</div><hr>
}
</div>
<button type="submit" class="full-width uppercase">Search Cheap Hotels</button>
</div>
}
</form>
</div>
</div>
I believe that when the redirection did not happen then on else part your view model binding is causing your dropdown value to get changed and hence the dropdown on change event triggers again and again. Make sure you are not changing the selected item of your dropdown from ajax call.

Categories

Resources