How to associate an event to Html.ActionLink in MVC3 - ajax

I have made an Ajax function but i am getting a big prolem in that.
I was displaying the contents on click of the link..
The links are fetched from the database and also the url of the links are fetched from the datbase.
I have wriiten ajax to call the contents dynamically on click of the link
<script type="text/javascript">
$(document).ready(function () {
$('a').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>
Now FetchUrlByHobbyName is the function called from the Controller thart returns the url
//Ajax routine to fetch the hobbyinfo by hobbyname
[HttpPost]
public ActionResult FetchUrlByHobbyName(string data)
{
HobbyMasters hobbymaster = new HobbyHomeService().FetchHobbyMasterByHobbyName(data);
string url = hobbymaster.InformationUrl;
if (HttpContext.Request.IsAjaxRequest())
return Json(url);
return View();
}
And in my View i have written the link like this:
#foreach (var item in Model)
{
<li >#Html.ActionLink(item.HobbyName, "Hobbies")
</li>
}
i tried this :
#Html.ActionLink(item.HobbyName, "Hobbies", null, new { id = "alink" })
and then calling Ajax on click of 'alink' but with this my ajax function doesnot get called.
Now the problem is the ajax function is getting called on click of every link on the page..
I want to assign a unique Id to it but i am not understanding how to do that
please Help me...

For that specific link, assign an id. E.g
<a id="someID" href="url">Link</a>
and than bind the click only with that link.
$('#someID').click(function (e)) ....

If I understood you correctly this helps you
The text of the link
<script type="text/javascript">
function myAjaxFunction(){
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
</script>

Try to give a css class selector to you action link like this...
#Html.ActionLink("some link", "Create", "Some_Controller", new { }, new { #class = "test" })
then User jquery for it..
<script type="text/javascript">
$(document).ready(function () {
$('.test').click(function (e) {
e.preventDefault();
var filename = $(this).text();
var Hobbyurl = '#Url.Action("FetchUrlByHobbyName")';
$.ajax({
type: "POST",
url: Hobbyurl,
data: { data: filename },
success: function (returndata) {
$('iframe').attr('src', returndata);
}
});
});
});
</script>

Related

Ajax post calling wrong url

Good day.
I want to know why is my project calling the wrong url? The code is:
SCRIPT
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
CONTROLLER
public class ApplicationController : Controller
{
public ActionResult Franchise()
{
return View();
}
}
I even tried changing the url by 'Url.Action("Franchise", "Application")' but still the system kept on bringing me to http://localhost:49267/Home/Franchise.
I can't understand what is wrong here. Is there a bug in jquery ajax url post?
Thanks in advance.
UPDATE
<button class="btn btn-success" type="button" id="btnCapture">Submit</button>
#section Scripts{
<script src="~/Scripts/webcam.min.js"></script>
<script src="~/Scripts/webcam.js"></script>
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<script language="JavaScript">
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('results').innerHTML =
'<img id="base64image" src="' + data_uri + '"/>';
} );
}
</script>
<script>
$(document).on("click", ".open-camera", function () {
var myBookId = $(this).data('id');
$(".modal-body #franid").val(myBookId);
})
</script>
<script>
$(function(){
$('#btnCapture').on('click', function(){
var file = document.getElementById("base64image").src;
var franid = $("#franid").val();
var sendInfo = {
Imagee: file,
FranIDD: franid
};
$.ajax({
type: "POST",
url: "/Application/Franchise",
data: JSON.stringify(sendInfo),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#myModal3').modal('hide'); //hide the modal
},
error: function () {
alert("Error while inserting data");
}
});
});
});
</script>
}
This is all my code.
Ok. So I found my problem. It was in my controller.
In my controller I tried adding return RedirectToAction("Franchise", "Home"); after the save command. As soon as I commented this, everything worked.
Thanks for the help again guys.
Please use the browser to access directly, not from within the IDE directly access, from the localhost:49267 should be from the IDE access, and you will write URL as http://www.google.com try.

Sharepoint Dropdown Choices Filter

I have a dropdown on a form. I have it set as unique entry for the list. That works fine, when a user selects an option that was already selected in a previous list entry they are notified when the save or submit the form. However I would rather remove the choice from the dropdown list if that selection was already made and exists in the list, that way they can't select something already selected.
Thanks for your help
We can use REST API to get all the exists dropdown items and then remove the downdown options in the new/edit form page. The following code for your reference.
<script src="//code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
removeDuplicateDropDowm("FilterDropDown");
});
function removeDuplicateDropDowm(fieldName){
var listId = _spPageContextInfo.pageListId.replace("{","").replace("}","");
var fieldHTML="";
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'"+listId+"')/items?$select="+fieldName;
$.ajax({
url: url,
method: "GET",
async:false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
$("select[title='"+fieldName+"'] option").each(function(){
for(var i=0;i<items.length;i++){
if(items[i][fieldName]==$(this).val()){
$(this).remove();
}
}
});
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
return fieldHTML;
}
</script>

Using ajax to update the currently page with Laravel

I have this ajax inside my file.php (It hits the success callback):
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
console.log(data);
}
});
})
</script>
Now on my Controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));
}
What I want to do:
I have a LIST with professor and their disciplines. What I need to do is:
Whenever I change the value of that select box, I just remake the function with the new parameter.
I'm trying to use ajax to remake that list but nothing change, not even the URL with the professor.php?anoSemestre=xx.
Also, when I try to use the $_GET['anoSemestre'] the page doesnt show any change or any ECHO.
But If I go to Chrome spector>NEtwork and click the ajax I just made, it shows me the page with the data I sent.
Cant find out what I'm doing wrong.
UPDATE
I did what was suggested me, now I'm working with the data I get from the success callback:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
var lista = $(data).find('#list-professores'); //Get only the new professor list and thier disciplines
$('#list-professores').remove(); //Remove old list
$('#professores').append(lista); //Append the new list where the old list was before.
}
});
})
</script>
The return of var lista = $(data).find('#list-professores'); is:
Accordion Effect
#list-professores li input[name='item']:checked ~ .prof-disciplinas {
height: auto;
display:block;
min-height:40px;
max-height:400px;
}
This list is an Accordion Menu (using a checkbox and changing it with js&css), so everytime I click on a professor < li>, it's suppose to open and show a sublist (disciplines of that professor I clicked). But it's not opening anymore and no errors on the console. No idea why.
The issue here is what you are returning in your controller and how you do it, you donĀ“t need to redirect or refresh the entire page. This could be achived using a single blade partial for the piece of code you may want/need to update over ajax. Assuming you have an exlusive view for that info, you could solve this with something like this:
in your view:
<div class="tableInfo">
<!--Here goes all data you may want to refresh/rebuild-->
</div>
In your javascript:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(){
$('.tableInfo').html(data); //---------> look at here!
}
});
})
</script>
in your controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
if (Request::ajax()) {
return response()->json(view('YourExclusiveDataPartialViewHere', ['with' => $SomeDataHereIfNeeded])->render()); //---------> This is the single partial which contains the updated info!
}else{
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));//---------> This view should include the partial for the initial state! (first load of the page);
}
}

Model is not passed to controller's action

I have the following code:
<script type="text/javascript">
$('#btnConfirmAddition').click(function () {
var contractorId = $("#contractorId").val();
var contactPerson = $("#addNewContactPersonForm").serialize();
$.ajax({
url: '#Url.Action("AddContactPerson", "Contractors")',
type: "GET",
data: { newContactPerson: contactPerson, contractorId: contractorId },
//data: contactPerson,
success: function (data) {
$("#myModal").modal('hide');
toastr.success("Success");
location.reload();
},
error: function (data) {
$("#errorArea").html(showError(data.ErrorMessage));
toastr.error(data.errorMessage);
}
});
return false;
});
</script>
public JsonResult AddContactPerson(ContactPerson newContactPerson, string contractorId)
{
//Some code
}
When I pass parameters in ajax call as above, my newContactPerson is null and contractorId contains appropriate data.
However when remove contractorId parameter from controller's action and pass parameter in ajax call as follows:
data: contactPerson
it works. I was wondering why? Can someone please help me?
post your data following way,
data: $("#addNewContactPersonForm").serialize() + '&contractorId='+ contractorId
And add data type to Ajax call,
dataType: "json"

ajax call with jquery asp.net mvc

I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:
<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/MyController/MyAction",
dataType: 'string',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
In MyController I have the following code:
public string MyAction()
{
return "test";
}
I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
{
if (Request.IsAjaxRequest())
{
//do something here
}
//do something else here
}
But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.
Change dataType: 'string' to dataType: 'text'
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/login/MyAction",
dataType: 'text',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
I check it my local it will work for me

Resources