Refresh images jquery - c#

I have uploading images with ajax form in my ASp.Net application. I need to refresh images, so I try this:
$(function () {
$(".fileUploadForm").ajaxForm({
success: function (data, text, xhr, form) {
var tmp = jQuery(this).closest("img[class=imageResource]").attr('src');
}
});
});
Here is my image:
<img class="imageResource" alt="picture" src="#Url.Action("Picture", new { id = Model.Id })" />
How can I find and rewrite image source with the same name
Update
Here is my html:
<div class="thumbnail">
<a target="_blank" href="/Template/OriginalPicture/8b8c824b-9605-4931-9fe2-1f5979baca42">
<img class="imageResource" src="/Template/Picture/8b8c824b-9605-4931-9fe2-1f5979baca42" alt="picture">
</a>
<div class="caption">
<div style="margin-bottom: 5px;">
<form class="form-horizontal fileUploadForm" method="post" enctype="multipart/form-data" action="/Template/PictureResource?resourceId=8b8c824b-9605-4931-9fe2-1f5979baca42&configId=aa383b5a-23b2-4780-965e-ef4e95cd3fa2&pageNumber=1">
<div class="input-append">
<input type="file" name="picture">
<input class="span1" type="text" size="128" style="width: 86px;">
<button class="btn browse" type="button"> ...</button>
<button class="btn" type="submit">Upload</button>
</div>
</form>
</div>
</div>

try this code:
$(function () {
$(".fileUploadForm").ajaxForm({
success: function (data, text, xhr, form) {
var tmp = form.closest('.thumbnail').find('.imageResource').attr('src');
form.closest('.thumbnail').find('.imageResource').attr('src', tmp + "?" + (new Date()).getTime());
}
});
});
I'm not sure if jQuery(this) will return a form (do not remember what is "this" there )
(new Date()).getTime() - is just to change image URL and force brower take image not from cache. Uh. And not noticed .closest - it will search for closest parent, and not for a child element. You may use .find for that.
form - that is a current from, according to docs closest('.thumbnail') will find parent with class .thumbnail closest to a form. .find('.imageResource') will search for an elements with class imageResource only inside .thumbnail. As there is only one image tag with class imageResource inside thumbnail - code above should work fine

Related

Call the same function

I would like whichever button been clicked I want to call the same function.
for now I have six card on View but work only one first. Other dosent work
My view
<h2>Our workouts</h2>
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="~/Content/not-found-image.jpg" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#item.Name</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
#*Go to anywhere*#
<a id="btnNewSave" class="btn btn-primary">Go to anywhere</a>
<input type="text" id="getValue" value="#item.Id" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
My controller:
[HttpGet]
public ActionResult ListCoach(int? Id)
{
var ChoachList = _TraningService.Coach(Id);
return View(ChoachList);
}
script
I call My script from View use helper section
#section scripts {
<script>
$(document).ready(function () {
$("#btnNewSave").click(function () {
var data = $("#getValue").val();
$.ajax({
type: "GET",
url: '/TrainingType/ListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/TrainingType/ListCoach';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
});
});
</script>
}
You should try this way, because your type of buttons are diffrent as per current scenario <a> and button so below way you could try.
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function PassToContoller(data) {
//alert(data);
$.ajax({
type: "GET",
url: '/UserLog/AnotherListCoach',
data: { id: data },
success: function (data) {
console.log(data);
window.location.href = '/appUser/ManageAccount';
return data;
},
error: function () {
$("#loader").fadeOut("slow");
console.log("error1");
}
});
}
$(document).ready(function () {
$("a[name=link]").on("click", function () {
var valueOfClickedTag = $(this).data("index");
alert("Clicked On Anchor: " + valueOfClickedTag);
var callFunc = PassToContoller(valueOfClickedTag)
});
$(":button[id=GoToAnywhere3]").on("click", function () {
var valueOfClickedBtn = $(this).data("index");
var callFunc = PassToContoller(valueOfClickedBtn )
});
});
</script>
}
Razor HTML:
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="col-md-4">
<div class="card" style="width: 18rem;">
#*<img src="~/Content/no_foto.png" class="card-img-top" alt="...">*#
<div class="card-body">
<h5 class="card-title">#item.StudentID</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<div id="textButton">
Go to anywhere
<a class="btn btn-primary" data-index="#item.Name" name="link">Go to anywhere</a>
<input class="btn btn-primary" type="button" id="GoToAnywhere3" data-index="#item.StudentID" value="Save" />
<input type="text" class="inputVal" id="getValue" value="#item.Name" hidden />
</div>
</div>
</div>
</div>
}
</div>
</div>
Output:
Note: <input type="text" class="inputVal" id="getValue" value="#item.StudentID" hidden /> is not needed anymore.
Hope it would completely resolve your problem.
Firstly make use of button type rather than an a. With that change, you can use the onclick event in two ways:
First opt:
<button class="btn btn-primary list-coaches" onclick="listCoaches()">List Coaches</button>
function listCoaches() { ... }
Second opt:
<button class="btn btn-primary list-coaches">List Coaches</button>
$('.list-coaches').click(function() { ... });

How to navigate to next tab in Razor pages after submitting first form

Is there anyway to navigate to next tab after submitting form in first tab in asp.net razor pages.
Currently im using return page() ,which will load first form.
You can overrride your form submit with Jquery and after submit you can change tab with jquery.
$("#yourFormId").submit(function (event) {
event.preventDefault();
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url: post_url,
type: request_method,
data: form_data
}).done(function (response) { //
// switch tab here
});
});
Is there anyway to navigate to next tab after submitting form in first tab in asp.net razor pages.
It seems that you are using Bootstrap navigation tabs in your Razor pages. To achieve the above requirement, you can try the following approaches.
Approach 1: store active tab info in localStorage while user click the submit button, then you can activate specific tab based on stored active tab info via JavaScript, like below.
<!-- Tab panes -->
<div class="tab-content">
<!-- STAFF DETAILS -->
<div role="tabpanel" class="tab-pane active" id="StaffDetails">
<br />
<form method="post" asp-page-handler="InsertStaffDetails">
Staff Details Partial Here
#*<partial name="_StaffDetails" />*#
<div style="float:right">
<input type='submit' class='btn btn-success' value='Save' onclick="setNextActiveTabFunc('Biodata')"/>
</div>
</form>
</div>
<!-- BIODATA -->
<div role="tabpanel" class="tab-pane" id="Biodata">
<br />
<form method="post" asp-page-handler="InsertBioData">
Bio Data Partial Here
#*<partial name="_BioData" />*#
<div style="float:right">
<input type='submit' class='btn btn-success' value='Save' onclick="setNextActiveTabFunc('EduQualification')" />
</div>
</form>
</div>
<!-- EDUCATIONAL QUALIFICATION -->
<div role="tabpanel" class="tab-pane" id="EduQualification">
<br />
<form method="post" asp-page-handler="InsertEduDetails">
Edu Details Partial Here
#*<partial name="_EduQualification" />*#
<div style="float:right">
<input type='submit' class='btn btn-success' value='Save' onclick="setNextActiveTabFunc('Assets')" />
</div>
</form>
</div>
#*do same on other submit button*#
JS code
<script>
function setNextActiveTabFunc(atab) {
localStorage.setItem("activeTab", atab);
}
$(function () {
var active_tab = localStorage.getItem("activeTab");
//remove localStorage item
//localStorage.removeItem("activeTab");
if (active_tab != "" && active_tab != null) {
$('#wizard a[href="#' + active_tab+'"]').tab('show');
} else {
$('#wizard a[href="#StaffDetails"]').tab('show');
}
})
</script>
Approach 2: Can achieve same by checking handler name through QueryString, then dynamically set active tab on client side.
$(function () {
var urlParams = new URLSearchParams(window.location.search);
var pre_handler = urlParams.get('handler');
switch (pre_handler) {
case "InsertStaffDetails":
//console.log("InsertStaffDetails");
$('#wizard a[href="#Biodata"]').tab('show');
break;
case "InsertBioData":
$('#wizard a[href="#EduQualification"]').tab('show');
break;
case "InsertEduDetails":
$('#wizard a[href="#Assets"]').tab('show');
break;
//...
//code for other tabs
//..
default: $('#wizard a[href="#StaffDetails"]').tab('show');
}
})
Test Result

How to put Partial View inside Bootstrap Modal?

I want to put a Partial View inside a Bootstrap Modal,
This is the JQuery code I'm using:
function CreateEmployeeModal()
{
var url = $("#btnCreateEmployeeModal").data("mine");
$.ajax({
type: 'get',
url: url
}).success(function (result) {
$(".modal-body").html(result)
$("#MyModal").modal('show')
}).error(function () {
alert("didn't work");
})
}
And this is the Modal code inside the _Layout file:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body" id="divModalBody">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
I'm firing the modal using this button from the Index page, I've created the data-mine attribute to save the url to the Action Method that is returning the PartialView:
<input type="button" class="aslink modal-link" data-toggle="modal"
data-target="#myModal" id="btnCreateEmployeeModal" value="Open Modal" data-mine="#Url.Action("CreateUsingModal")">
This is the controller action method I have to return the Partial View:
public PartialViewResult CreateUsingModal()
{
return PartialView();
}
The operation is having success in ajax, but the modal doesn't show...
I had an error..., I should use a lowercase instead of a uppercase for the id of the modal... The correct way is: $("#myModal").modal('show')
I'll assume your GET endpoint (your method) is returning raw HTML.
A better way of doing this would be for your method to return your data in JSON format and then use that data to populate your modal window:
function CreateEmployeeModal()
{
var url = $("#btnCreateEmployeeModal").data("mine");
$.ajax({
type: 'get',
url: url
}).success(function (result) {
console.log(result); //better than alert
$("#textboxCorrespondingToValue").val(result.valueCorrespondingToTextbox);
$("#MyModal").modal('show');
}).error(function () {
alert("didn't work");
})
}
This way, if you even need to change the html you don't have to change anything in your server side code

My ajax post will not stop running (C#,JQuery,Ajax)

My Ajax call works. It sends data to the database as expected.
However, after it completes this task, it will not call the success or fail function. It just keeps running. I set the timeout for the ajax call but it didn't work.
I have a form in my html page
<form class="form-horizontal" id="signupForm" role="form" method="post" name="signupForm" action="">
<div class="form-group">
<label class="col-xs-3 control-label" for="TextBoxUsername">Username:</label>
<div class="col-xs-9"><input type="text" placeholder="username" id="TextBoxUsername" class="form-control" /></div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label" for="TextBoxPassword">Password:</label>
<div class="col-xs-9"><input type="text" placeholder="password" id="TextBoxPassword" class="form-control" /></div>
</div>
<div class="form-group">
<label class="col-xs-offset-5 control-label" for="selectImage" style="font-weight:bold;font-size:15px;">Choose Your Avatar</label>
</div>
<div class="content">
// I used the Image-Picker jQuery plugin here to create a selection of images and show them as thumbnails
<select name="selectImage" class="image-picker" id="selectImage" form="signupForm">
<option class="grid-item" data-img-src="img1.png" value="img1.png">Image 1</option>
<option class="grid-item" data-img-src="img2.png" value="img2.png">Image 2</option>
<option class="grid-item" data-img-src="img3.png" value="img3.png">Image 3</option>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</form>
This is my jQuery:
// this is my main jQuery function
$(function () {
// this is my form submit function
$("form").submit(function (e) {
e.preventDefault(); // this stops the form from refreshing the page
create();
});
});
// this function creates an object to be added to the database
function create() {
user = new Object();
user.Username = $("#TextBoxUsername").val();
user.Password = $("#TextBoxPassword").val();
// here I am getting the value of the selected item from <select> div
selectedImage = document.signupForm.selectImage.options[document.signupForm.selectImage.selectedIndex].value;
// this is just to convert the image to base 64 string.
var img = new Image();
img.src = selectedImage;
// draw canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0,0);
var imageURL = canvas.toDataURL();
user.Image = imageURL;
// end base 64 string conversion
$.ajax({
type: "Post",
url: "api/signup", // this url goes to a controller, it works perfectly
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
timeout: 3000, // does not do anything!
success: function () {
// this function is not being called!
$("#lblstatus").text("User was created!");
},
error: function (jqXHR, textStatus, errorThrown) {
// this function is not being called either!
errorRoutine(jqXHR);
}
});
}; // end create function
Like I said, the database is receiving the data just fine. But for some reason, this ajax call will not stop running. If I manually stop the application from the debugger, I can check the database and everything worked. I just need this ajax call to complete.
Try changing the type to button and set an id to it <button type="button" class="btn btn-default" id="submitbtn" >Sign in</button> And handle it by jquery click function $("#submitbtn").click(function () {
create();
});
by that, the page will not refresh even if you don't have the e.preventDefault();
since your using an ajax, the form is not needed anyway. So it can work even if you don't have a form tag
I found the tiny typo culprit.
it was inside the success function. I didn't add the "#" in front of "("lblstatus"). It should have been ("#lblstatus").
silly silly mistake.
Thanks for all the suggestions. It turned out to be a typo afterall.

Pass javascript value to controller C#

I have created a search function on my website that allows the user to select what table they wnat to search for. The select list is within a dropdown rendered within a dropdown menu using bootstrap. The issue I'm facing is that when the form is run the value of the selected item from the dropdown menu that is passed into the controller is "" instead of the value that was selected in the dropdown menu.
Any help would be grateful.
** search function**
<div class="col-lg-6">
#{using (Html.BeginForm("Results", "Searchv2", FormMethod.Get))
{
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
<ul class="dropdown-menu">
#foreach (var searchType in new[] { "User", "Restaurant", "Cuisine" })
{
<li>#searchType</li>
}
</ul>
<input type="hidden" name="SearchBy" />
</div>
<input type="text" class="form-control" placeholder="Search" name="SearchString" id="SearchString">
</div>
}}
</div>
jquery that finds the value
<script>
$(".dropdown-menu").click(function () {
$("input[name='SearchBy']").val($(this).html());
});
</script>
you have to write click event on anchor tag, as you have anchor tag inside <li> like this:
<ul class="dropdown-menu">
<li>
<a>SearchText</a>
</li>
</ul>
$(".dropdown-menu li a").click(function () {
$("input[name='SearchBy']").val($(this).html());
});
I believe you want to set the SearchBy value by getting the value of the selected item:
<script>
$(".dropdown-menu").click(function () {
$("input[name='SearchBy']").val($(this).val());
});
</script>
if you want to get the value of text in between the <a></a> tags, try use .text() instead of html()
First you are selecting the ul not the a inside its li and second you should use jquery text function:
<script>
$('.dropdown-menu li a').click(function (e) {
e.preventDefault();
$('input[name="SearchBy"]').val($(this).text());
});
</script>

Categories