I have two views (create/edit) that require the same javascript for client-side functions. I want to place my javascript into a separate file so I can reference/reuse the script on both my views but I cannot do this because I am using MVC extension methods in my javascript.
For example:
$.ajax({
type: 'GET',
url: '#Url.Action(MVC.Attribute.GetTargetedOrganisationAttributeScope())',
traditional: true,
data: { organisationIDs: ids },
success: function(data) {
// ...
}
}
});
One method I found was to place my javascript in a partial view and reference that as it allows me to use MVC extensions. Is this the correct method? Is there a better way of achieving this?
#section Scripts{
#{
Html.RenderPartial(MVC.Attribute.Views.ViewNames._js);
}
}
View
function BuscarPaciente() {
var identificacion = $("#identificacion").val();
$.ajax({
url: "#Url.Action("BuscarDatos")",
data: { identificacion: identificacion },
type: "POST",
success: function(response) {
$("#resultado").hide("slow", function() {
$(this).html(response);
$(this).show("slow");
});
}
});
};
Controller
public ActionResult BuscarDatos(string identificacion)
{
CAPBAS capbas = db.CAPBAS.SingleOrDefault(c => c.MPCedu == identificacion);
return PartialView("DatosUsuario", capbas);
}
Related
I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri
I'm outputting API data on separate pages coming from different end point urls, ie. https://api.server.com/first, https://api.server.com/second, etc.
The code is working, but it seems awfully redundant and I'm sure there's a better way of expressing this that's more optimal and faster:
var $rubys = $('#rubys');
$(function () {
$('#loading-rubys').show();
$.ajax({
type: 'GET',
url: 'https://api.server.com/first/',
success: function(rubys) {
$.each(rubys, function(i, ruby) {
$rubys.append('$'+parseFloat(ruby.price).toFixed(2)+' |
$'+parseFloat(ruby.attribute).toFixed(0));
});
},
complete: function(){
$('#loading-rubys').hide();
}
})
});
var $emeralds = $('#emeralds');
$(function () {
$('#loading-emeralds').show();
$.ajax({
type: 'GET',
url: 'https://api.server.com/second/',
success: function(emeralds) {
$.each(emeralds, function(i, emerald) {
$emeralds.append('$'+parseFloat(emerald.price).toFixed(2)+' |
$'+parseFloat(emerald.attribute).toFixed(0));
});
},
complete: function(){
$('#loading-emeralds').hide();
}
})
});
The following:
var $rubys = $('#rubys');
$('#loading-rubys').show();
are set for each post page using YAML front-matter (Jekyll) like so:
---
title: Post about Ruby
var-id: rubys
load-id: loading-rubys
---
and output them in HTML:
<div id="{{ page.var-id }}">
<div id="{{ page.load-id }}">
<img src="/assets/img/loading.svg"/>
</div>
</div>
Current workflow
So basically whenever I create a new post, I:
Set the var-id and load-id custom parameters for each post in the front-matter
Create a new function to include those and make a new GET request to the respective url, ie. https://api.server.com/third/, https://api.server.com/fourth/.
How would you write this better?
Something like this could help.
function getGems(gems,gemsURL) {
var $gems = $('#'+gems);
$('#loading-'+gems).show();
$.ajax({
type: 'GET',
url: gemsURL,
success: function(data) {
$.each(data, function(i, v) {
$gems.append('$'+parseFloat(v.price).toFixed(2)+' |
$'+parseFloat(v.attribute).toFixed(0));
});
},
complete: function(){
$('#loading-'+gems).hide();
}
});
}
$(function () {
getGems('rubys','https://api.server.com/first/');
getGems('emeralds','https://api.server.com/second/')
});
I'm creating asp.net mvc 5 application.In that application I want generate a Folder once I click a button on front end view page.
I want to generate that folder with in following location ~/Essential_Folder/
<input type = "button" value="Create_Folder" class="btn btn-default" id="create_folder"/>
How can I do this ,
can I do this using Server side language (in my case its C#), if its how ?
is this possible to do using client side language (such as JavaScript) ?
script
<script type="text/javascript">
$('btn-default').click(function () {
});
</script>
As #Stephen mentioned, you need to use ajax in order to create a folder. So you can have an action method like this:
[HttpPost]
public JsonResult CreateDirectory()
{
//if location has folder called "Essential_Folder" it should allow to goto inside of this if condition
if (Directory.Exists(Server.MapPath("~/Content/Essential_Folder/")))
{
Directory.CreateDirectory(Server.MapPath(string.Format("~/Content/Essential_Folder/NewDir_{0}",
DateTime.Now.Millisecond)));
return Json("OK");
}
return Json("NO");
}
And your ajax call should something like this:
<script type="text/javascript">
$('.btn').click(function() {
$.ajax({
url: "#Url.Action("CreateDirectory")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
if (response === 'OK')
alert("Directory has been created");
else
alert("errro");
}
});
});
</script>
Senario :
I wanna call a Helper method from JavaScript.I produced some controls in server side such as Grid,DataTimePicker,SlideShow, ... for ASP.NET MVC.
Now, how do I invoke helper method from JavaScript ?
I found the way for invoke helper method in view(ASP.NET MVC) .
for example:
namespace Component
{
public class HelperMethod
{
public static MvcHtmlString GridSort(this HtmlHelper helper,string fieldName)
{
//do something
}
}
}
Code in my view:
#using Component
<script>
$(document).ready(function(){
var message='FirstName';
var result = "#Html.GridSort(message)"; // here is the Error
$("div#grdUsers").html(result );
});
</script>
<div id="grdUsers">
//grid elements
</div>
Now, the problem is : I can't pass JavaScript Variable(message) value to helper method(GridSort).
What can I do ?
1st Way:- make it an ACTION returning json - and call with Ajax.
#using Component
<script>
$(document).ready(function(){
var message='FirstName';
$.ajax({
url: '/Your Controller name /your Method name',
type: 'POST',
data: {message:message},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () {
},
error: function (error) {
alert('error');
}
});
});
</script>
<div id="grdUsers">
//grid elements
</div>
2nd Way:-use Request.QueryString["message"]
Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});