ajax unable to find url c# method - javascript

I am unable to find the url in my ajax call. Below is the Html code
<div class='replyDiv1' id='sendmail_form'>
<h2>Reply</h2>
<label>Subject:</label><span class='replySubject'>Reply: #=MessageSubject#</span><br />
<label class='datereply'>Date:</label><span class='replytime'></span><br />
<label>To:</label><span>#=MailFrom#</span><br />
<label class='claimIDReply'>Claim:</label><span>#=ClaimId#</span>
<label>Message:</label><br /><textarea rows='8' style='width:80%;' class='replymessage' placeholder='Reply Here'></textarea><br /><br />
<button class='btn btn-primary' onclick='button1()' id='sendReply'>Send</button><br /><br /><span id='msg' style='color:red;'/>
</div>
Here is the JavaScript Ajax Code, this is inside the View
var dataObject1 = JSON.stringify({
'MailTo': from,
'MailFrom': to,
'ClaimId': claimID,
'CreateDate': time,
'MessageBody': newMessage,
'MessageSubject': subject,
});
$.ajax({
type: "Post",
datatype: "json",
url: '#Url.Action("SendReply1", "MCenterController")',
data: {},
cache: false,
//contentType: 'application/json',
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Fail");
},
});
Below is the C# method
[HttpPost]
[ValidateInput(false)]
public ActionResult SendReply1()
{
return Json(new { success = true, message = "Success" }, JsonRequestBehavior.AllowGet);
}
When I debug the code in Chrome, I get the error that MCenterController/SendReply1 is not found and the ajax call fails. SendReply1 is the name of the method and MCenterController is the name of the controller.
I need the button to refresh the current page.
What am I missing?

Related

Js function passes null to the controller, in the old version

I need to wrote a code on an older version of the .net Framework, namely 4.5.2.
I ran into a problem, the ajax code sends an empty request to the controller.
Here is the form and I need to check user Full Name on unique:
<div class="register-card">
<h1>Register the new user</h1>
#using (Html.BeginForm("CreateUserAsync", "Home", FormMethod.Post))
{
<div>
#Html.Label("FullName", "Enter your full name")
<input type="text" id="FullName" name="FullName" pattern="^(\w\w+)\s(\w+)\s(\w+)$" onblur="CheckAvailability()" required />
<span id="message" onclick="ClearMessage()"></span>
</div>
<p><input type="submit" value="Send" id="submit" /></p>
}
</div>
Here is my js function to checking Full Name:
function CheckAvailability() {
var data = $("#FullName").val();
var param = data;
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "String",
data: JSON.stringify(param),
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
};
function ClearMessage() {
$("#message").html("");
};
Js function pass the FullName to next controller:
[HttpPost]
public async Task<JsonResult> CheckFullNameAsync([FromBody]string fullName)
{
var isValid = await _service.IsUserExistAsync(fullName);
return Json(isValid);
}
But the controller receives null.
I think the problem is in the Js function, but I can figure out what I'm doing wrong.
Dont need to create two variable
var data = $("#FullName").val();
var param = data;
Just create
var param = $("#FullName").val();
try this
Check this link. it explains your problem well
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: 'json',
data:{"":param},
//data: { fullName: param },
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
or this one also
$.post('/Home/CheckFullNameAsync', { fullname: param},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
What is dataType: "String"? That's not a listed option. And more specifically, all you're sending is a value but with no key. So the server isn't able to deserialize the data and determine where the fullName value comes from.
Change the type to 'json' and send the object with the named key for the value:
dataType: "json",
data: { fullName: param },

Call Action Method on button click ASP.NET MVC

I am trying to get user input in button click.
When user insert number and press Check, it needs to return xml data type.
So in my controller I create function which will return a data for passing ID
[ResponseType(typeof(AKONTA))]
public IHttpActionResult GetAKONTA(string id)
{
AKONTA aKONTA = db.AKONTAS.Find(id);
if (aKONTA == null)
{
return BadRequest("Ne postoji A_KONTO pod tim rednim brojem");
}
return Ok(aKONTA);
}
And In my View I have following
<br /><br />
<form>
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<a asp-action="Index" class="btn btn-primary" id="aKonto" action="#Url.Action("GetAKONTA", "Akontas")">Provjeri</a>
</div>
</form>
And I want to create in btn click when user pass ID it needs to return XML data format.
SO far I create a JS function, but I don't know JavaScript and don't know the logic how to pass Controller Action Result to JS.
<script>
$(document).ready(function () {
$('#aKonto').click(function () {
document.getElementById("aKonto").onclick = function () {GetAKONTA()};;
});
});
</script>
If someone can help me I would be very thankful.
Cheers !
UPDATE
function aKontoSubmit() {
$.ajax({
type: "GET",
url: 'api/Akontas',
//data: { id: id },
dataType: "xml",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
**routeConfig**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AkontasWebApi
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Add Reference of Jquery, to try the ajax call method.
function aKontoSubmit() {
$.ajax({
type: "POST",
url: '/Akontas/GetAKONTA',
data: $('form').serialize(),
dataType: "json",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Error while inserting data");
}
});
}
Change you Link Code as Below
<a asp-action="Index" class="btn btn-primary" id="aKonto" onClick='return aKontoSubmit() '>Provjeri</a>
Or Else You Can try if you are using ASP.Net MVC Core Development
<form asp-action="GetAKONTA" asp-controller="Akontas" method="post">
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<input class="btn btn-primary" id="aKonto" type = "submit" value = "Provjeri" />
</div>
</form>
After a couple hours of debugging and searching I found that I forget to put
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
This is location where should redirect if item exsist in database
And URL call need to be modified as well
URL: "/api/Akontas/GetAKONTA",
function aKontoSubmit() {
$.ajax({
type: "GET",
URL: "/api/Akontas/GetAKONTA",
data: { id: $('#AkontasId').val() },
contentType: "data/xml; charset=utf-8",
success: function (result) {
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}

AJAX Delete Not Working Entity Framework

I wonder why its not working, here is the code
View
<input type="button" value="Delete" onclick="deletefunction(#item.PhotoId)"/>
Controller
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return null;
}
JQUERY/AJAX
<script type="text/javascript">
$(document).ready(function () {
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
};
});
</script>
im new to jquery and ajax, im trying to delete the photo without refreshing the page, am i in the correct path?
I would suggest to attach click event to your button instead of writing javascript in markup. Consider the below markup:
<input type="button" class="delete" value="Delete" data-picid="#item.photoId"/>
Now attach a click event to .delete as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
//access message from server as result.message and display proper message to user
alert: ("Success")
},
error: {
alert: ("Error")
}
});
});
Your Controller then:
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return Json(new{ message=false},JsonRequestBehavior.AllowGet);//return false in message variable
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return Json(new{ message=false},JsonRequestBehavior.AllowGet); //return true if everything is fine
}
Once photo is deleted based on the success or failure your can do it as below in success of ajax, but before that store a reference to yourbutton` as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
var $this=$(this);
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
if(result.message)
{
$this.closest('yourrootparentselector').remove();
//here yourrootparentselector will be the element which holds all
//your photo and delete button too
}
},
error: {
alert: ("Error")
}
});
});
UPDATE
Based on your given mark up you I suggest to add one more root parent for your each image and delete button as below:
<div style="margin-top: 17px;">
<div id="links">
#foreach (var item in Model.Content)
{
<div class="rootparent"> <!--rootparent here, you can give any classname-->
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
</div>
Now you can write this in success
$this.closest('.rootparent').remove()
Try this.
<script type="text/javascript">
$(document).ready(function () {
});
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
}
</script>

Passing localstorage to controller using Ajax

I need to access the data held in localstorage, server side but that's another story.
I have this button in my view:
<div style="float:right;">
<input id="btnTest" type="button" name="test Json Button" value="test Json Button" onclick="sendLocalStorage();" class="btn btn-default" />
</div>
This JS function:
function sendLocalStorage() {
var JsonLocalStorageObj = JSON.stringify(localStorage);
//var test = ["test1", "test2", "test3"];
$.ajax({
url: "/MyControllersName/Test",
type: "POST",
dataType: 'json',
data: JsonLocalStorageObj,
contentType: "application/json; charset=utf-8",
beforeSend: function () { alert('sending') },
success: function (result) {
alert(result.Result);
localStorage.clear();
}
});
};
And this test controller method:
[HttpPost]
[WebMethod]
public ActionResult Test(string JsonLocalStorageObj)
{
string x = JsonLocalStorageObj;
//deserialize here
return RedirectToAction("Index");
}
When I run JSON.stringify(localStorage); in chrome dev tools, I see data as expected, however when I debug my controller JsonLocalStorageObj is always null. As a test I used the test array that is commented out and set the parameter on the controller to accept a List<string> and this came through populated.
Whats the problem with JSON.stringify(localStorage); being passed through?
You haven't specified the parameter name of your action (JsonLocalStorageObj) and your content and dataType were wrong too.
Try change your javascript code to this:
function sendLocalStorage() {
var JsonLocalStorageObj = JSON.stringify(localStorage);
//var test = ["test1", "test2", "test3"];
$.ajax({
url: "/MyControllersName/Test",
type: "POST",
data: { JsonLocalStorageObj: JsonLocalStorageObj },
success: function (result) {
alert(result);
}
});
}

how to get value by .ajax() method in codeigniter and show the value in input field?

sorry for ask this question again , but I still don't slove this problem!!
half years ago , I got some problem about receive value from server , and show the value in input field.
the question is below:
when I click the button "new" , and I can get the max number from ID table.
I write some code for this and try to use AJAX receive and show in input, it's not working,if I open the debug tools in chrome,I will get a error message :"Uncaught ReferenceError: maxnum is not defined "
(when I only use browser to open the page /localhost/index.php/static_data/kungfu_maxquery,I can get correct json and print on screen. )
what else I can do ...... Σ(  ̄□ ̄;)
sorry again , sorry all , I am a construction laborer , don't know too much about program code, I read the book and practice along , please teach me .
View : (views/kungfu.php)
<div class="hero-unit">
<div style="width:250px;float:left;">
<form id="pr_form" action="<?php echo site_url();?>/static_data/kungfu_act" method="post">
ID:<input id="num" name="num" type="text" class="field_set"><br>
NAME:<input id="name" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" name="kungfu" type="text" class="field_set"><br>
</div>
<div style="clear:both;height:50px;padding-top:10px">
<input id="go" name="go" class="btn" type="submit" value="submit">
<input id="query" name="query" class="btn" type="button" value="query">
<input id="newone" name="newone" class="btn" type="button" value="new">
</div>
</form>
</div>
Controller(controllers/static_data.php):
class Static_data extends CI_Controller {
public function kungfu_maxquery()
{
$this->load->model("pr_model");
$data = $this->pr_model->pr_maxquery();
echo json_encode($data);
}
}
Model(models/pr_model.php):
class Pr_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('html');
$this->load->database();
}
function pr_maxquery()
{
$this->db->select_max("num");
$maxquery=$this->db->get("kungfu_table");
return $maxquery;
}
JS(js/try.js):
$("#newone").click(function () {
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
cache: "false",
data: {'num':maxnum},
datatype: "json",
}).done(function () {
$("#num").val(maxnum);
});
});
In the data of the ajax call you are setting the data, not getting!!!
You should use something like this:
$("#newone").click(function () {
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
cache: "false",
datatype: "json",
}).done(function (result) {
$("#num").val(result);
});
});
The function in the done recibe the result of the callback.
you try like this
$("#newone").click(function () {
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
cache: "false",
datatype: "json",
}).done(function (resp) {
var json = $.parseJSON(resp);
$("#num").val(json);
});
});

Categories