descomentar la siguiente línea del web service:
<System.Web.Script.Services.ScriptService()> _
Llamado a un webservice asmx con AJAX
Código .NET
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports LibX.X
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
<WebMethod> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Sub ObtenerChoiceListItems2(ByVal cobnamtab As String, ByVal filtro As String)
Dim js As New JavaScriptSerializer()
Context.Response.Clear()
Context.Response.ContentType = "application/json"
Dim d As String = "{ " +
"'datos': { " +
"'items': [{ " +
" 'coddestab': '5', " +
" 'deslartab': 'DESC ITEM 5' " +
" }, { " +
" 'coddestab': '10', " +
" 'deslartab': 'DESC ITEM 10' " +
" }, { " +
" 'coddestab': '15', " +
" 'deslartab': 'DESC ITEM 15' " +
"}]" +
"}" +
"}"
Context.Response.Write(js.Serialize(d))
End Sub
function getJSON(data_obj)
{
if (data_obj.d)
data_ok = data_obj.d;
else
data_ok = data_obj;
evalJson = eval("var varJSON = " + data_ok + ";");
return varJSON;
}
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports LibX.X
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
<WebMethod> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Sub ObtenerChoiceListItems2(ByVal cobnamtab As String, ByVal filtro As String)
Dim js As New JavaScriptSerializer()
Context.Response.Clear()
Context.Response.ContentType = "application/json"
Dim d As String = "{ " +
"'datos': { " +
"'items': [{ " +
" 'coddestab': '5', " +
" 'deslartab': 'DESC ITEM 5' " +
" }, { " +
" 'coddestab': '10', " +
" 'deslartab': 'DESC ITEM 10' " +
" }, { " +
" 'coddestab': '15', " +
" 'deslartab': 'DESC ITEM 15' " +
"}]" +
"}" +
"}"
Context.Response.Write(js.Serialize(d))
End Sub
Código javascript:
function cargarChoiceList(vNombreCombo, vCobnamtab)
{
jQuery.support.cors = true;
rndAux = '&random=' + Math.floor(Math.random()*9999999999);
jqxhr2 = jQuery.ajax({
type:"GET",
data:{ cobnamtab: vCobnamtab,
filtro:"",
rnd: rndAux},
dataType:"json",
url:"http://" + window.self.location.hostname + "/wsX/Parametros.asmx/ObtenerChoiceListItems2",
beforeSend:function(){
}
}).fail(function(jqXHR, textStatus){
alert("Error: " + "Status: "+
jqXHR.status +" detalle: "+ textStatus +
" detalle: "+ jqXHR.responseText);
}).success(function(data){
var v = getJSON(data);
$("[name=" + vNombreCombo + "]").empty();
for (i=0; i<v.datos.items.length; i++)
{
$("[name=" + vNombreCombo + "]").append($('<option>', {
value: v.datos.items[i]["coddestab"],
text : v.datos.items[i]["deslartab"]
}));
}
});
}
function getJSON(data_obj)
{
if (data_obj.d)
data_ok = data_obj.d;
else
data_ok = data_obj;
evalJson = eval("var varJSON = " + data_ok + ";");
return varJSON;
}
Ejemplo de llamado:
cargarChoiceList('WFF-SINO3', 'BANCOS');
Thermistor NTC3950 de 100K con Arduino
Codigo:
#include <math.h>
double Thermistor(int RawADC) {
double Temp;
Temp = log(10000.0*((1024.0/RawADC-1)));
Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
Temp = Temp - 273.15;
Temp = (Temp * 9.0)/ 5.0 + 32.0;
return Temp;
}
void setup() {
Serial.begin(9600);
}
void loop() {
int val;
double tempFahrenheith;
val=analogRead(2);
tempFahrenheith=Thermistor(val);
double tempCelcius = (tempFahrenheith - 32) * 5/9;
Serial.print("Temperature = ");
Serial.print(tempCelcius);
Serial.println(" C");
delay(1000);
}
Breakpoint aparece en amarillo y muestra el error "No se pueden cargar los simbolos"
Primero ejecutar la aplicacion.
Luego ir a Debug / Windows / Modules
Luego ir a Debug / Windows / Modules
elegir el assembly que corresponda al sitio (ej, RetWeb.dll)
Click derecho, y seleccionar "Symbol Load Information"
Start debugging, as soon as you've arrived at a breakpoint or used Debug > Break All, use Debug > Windows > Modules. You'll see a list of all the assemblies that are loaded into the process. Locate the one you want to get debug info for. Right-click it and select Symbol Load Information. You'll get a dialog that lists all the directories where it looked for the .pdb file for the assembly. Verify that list against the actual .pdb location. Make sure it doesn't find an old one.
In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe. The bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with itExportar datos a un archivo de texto con MySql
*** Tener en cuenta que el archivo se genera en el servidor de MySql ***
SELECT *
INTO OUTFILE '/mantis/out.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM mantis_custom_field_string_table
SELECT *
INTO OUTFILE '/mantis/out.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM mantis_custom_field_string_table
Formato de fechas al exportar un dataset a XML
Cuando se exporta un dataset a XML, las fechas se formatean según la timezone del equipo donde se está ejecutando la exportación.
Ej, si la fecha es
2003-04-06T00:00:00
cuando se exporta a XML puede quedar así
2003-04-06T00:00:00-03:00
En este caso le agregó el GMT -3
Una solución posible es cambiar el DateTimeMode del dataset a Unspecified.
De esta forma, no se incluirá el offset (el -3) en el archivo XML.
Fuente: http://blog.scosby.com/post/2013/03/01/Serializing-A-DataSet-With-DateTime-Columns.aspx
Ej, si la fecha es
2003-04-06T00:00:00
cuando se exporta a XML puede quedar así
2003-04-06T00:00:00-03:00
En este caso le agregó el GMT -3
Una solución posible es cambiar el DateTimeMode del dataset a Unspecified.
De esta forma, no se incluirá el offset (el -3) en el archivo XML.
System.Data.DataSet data = new DataSet();
// ...
// Iterate the columns and set DataColumn.DateTimeMode
// to DataSetDateTime.Unspecified to remove offset
// when serialized.
foreach (DataTable table in data.Tables)
{
foreach (DataColumn item in table.Columns)
{
// Switching from UnspecifiedLocal to Unspecified
// is allowed even after the DataSet has rows.
if (item.DataType == typeof(DateTime) &&
item.DateTimeMode == DataSetDateTime.UnspecifiedLocal)
{
item.DateTimeMode = DataSetDateTime.Unspecified;
}
}
}
Crear un componente con PCB Wizard
http://www.new-wave-concepts.com/files/PWtutor5.pdf
1. Agregar los pads que se necesiten (insert / pad)
2. Ir a Edit / Symbol / Insert Pin y hacer click en el centro de cada pad (esto es lo que permite luego conectar componentes entre si)
3. Ir a View / Coordinates / Origin / Change Origin, y hacer click en la esquina inferior izquierda del componente.
4. Crear con recuadros, circulos, etc, el formato del componente.
5. Seleccionar todo, click derecho, Arrange / Group
6. Hacer click derecho en el componente, ir a Edit / Symbol / Make Symbol, elegir Circuit Symbol, definirle una key (con la que se identificara en el pcb wizard, un nombre y una descripcion)
7. Click derecho en el componente, Symbol / Add to Library, y elegir la libreria en la que se quiere agregar.
1. Agregar los pads que se necesiten (insert / pad)
2. Ir a Edit / Symbol / Insert Pin y hacer click en el centro de cada pad (esto es lo que permite luego conectar componentes entre si)
3. Ir a View / Coordinates / Origin / Change Origin, y hacer click en la esquina inferior izquierda del componente.
4. Crear con recuadros, circulos, etc, el formato del componente.
5. Seleccionar todo, click derecho, Arrange / Group
6. Hacer click derecho en el componente, ir a Edit / Symbol / Make Symbol, elegir Circuit Symbol, definirle una key (con la que se identificara en el pcb wizard, un nombre y una descripcion)
7. Click derecho en el componente, Symbol / Add to Library, y elegir la libreria en la que se quiere agregar.
CS0103: The name 'Json' does not exist in the current context
Dentro del tag <compilation> agregar lo siguiente:
<assemblies>
<add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
<assemblies>
<add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
Invocar un método por su nombre en C# con Invoke
Type thisType = this.GetType();
En el caso en que sea un método privado, agregar estos parametros:
MethodInfo theMethod = thisType.GetMethod("nombre-del-metodo", BindingFlags.NonPublic | BindingFlags.Instance);
Si el método es público:
MethodInfo theMethod = thisType.GetMethod("nombre-del-metodo");
var msg = (TipoDeDatoQueDevuelveElMetodo)theMethod.Invoke(this, new[] { param });
Ej, si se llama a un actionresult:
var msg = (TipoDeDatoQueDevuelveElMetodo)theMethod.Invoke(this, new[] { param });
En el caso en que sea un método privado, agregar estos parametros:
MethodInfo theMethod = thisType.GetMethod("nombre-del-metodo", BindingFlags.NonPublic | BindingFlags.Instance);
Si el método es público:
MethodInfo theMethod = thisType.GetMethod("nombre-del-metodo");
Para ejecutarlo: (observar que param es el parametro que se le pasa al metodo:
var msg = (TipoDeDatoQueDevuelveElMetodo)theMethod.Invoke(this, new[] { param });
Ej, si se llama a un actionresult:
var msg = (TipoDeDatoQueDevuelveElMetodo)theMethod.Invoke(this, new[] { param });
Enviar datos desde javascript hacia un controller con AJAX en MVC
Método #1: Enviar form como JSON y otros parametros
Llamado Ajax
var f = $("#form_refin").serializeFormJSON();
var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
jqxhr2 = $.ajax({
type: "POST",
data: send,
dataType: "json",
url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
beforeSend: function () {
//l.start();
}
}).fail(function (jqXHR, textStatus) {
//l.stop();
alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
}).success(function (data) {
$("#HashSup").val(data);
});
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Controller
using Newtonsoft.Json;
...
...
...
[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{
var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
Método #2: Definir el objeto que se va a enviar manualmente
Llamado Ajax
$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}
jqxhr2 = $.ajax({
type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});
Controller
[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }
public class Usuario
{
public string Documento { get; set; }
public string Email { get; set; }
public string Nombre { get; set; }
public string TipoDoc { get; set; }
}
Método #3: Enviar el Modelo completo
Controller
Método #4: Enviar el form serializado
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)
Llamado Ajax
jqxhr2 = $.ajax({
}).fail(function (jqXHR, textStatus) {
if (data.MsgError == "Refinanciación contabilizada correctamente.") {
type: "GET",
data: $('form').serialize(),
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")",
beforeSend: function () {
$.blockUI({
message: 'Espere por favor...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: 0.5,
color: '#fff'
}
});
}
$.unblockUI();
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$.unblockUI();
$("#div_mensaje").html(data.MsgError);
$("#btn_contabilizar").attr("disabled", "disabled");
$("#btn_calcular").attr("disabled", "disabled");
}
});
Llamado Ajax
var f = $("#form_refin").serializeFormJSON();
var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
jqxhr2 = $.ajax({
type: "POST",
data: send,
dataType: "json",
url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
beforeSend: function () {
//l.start();
}
}).fail(function (jqXHR, textStatus) {
//l.stop();
alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
}).success(function (data) {
$("#HashSup").val(data);
});
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
Controller
using Newtonsoft.Json;
...
...
...
[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{
var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
}
Método #2: Definir el objeto que se va a enviar manualmente
Llamado Ajax
$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}
jqxhr2 = $.ajax({
type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});
Controller
[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }
public class Usuario
{
public string Documento { get; set; }
public string Email { get; set; }
public string Nombre { get; set; }
public string TipoDoc { get; set; }
}
Método #3: Enviar el Modelo completo
De esta forma se puede enviar el modelo desde la vista hacia un controller, cualquiera sea su estructura y complejidad.
Funciona con POST y GET, en este ejemplo se utiliza POST.
*** Tener en cuenta que utilizando este método NO se envían los datos modificados manualmente en el formulario o los datos cargados mediante javascript. Para poder hacer esto, utilizar el método 3 ***
Código en la View
Formulario:
@using Creditos.ViewModels.Liquidaciones
@model RefinanciacionArrendamientoVM
...
...
...
Llamado Ajax
var model = JSON.parse('@Html.Raw(Json.Encode(Model))');
jqxhr2 = $.ajax({
type: "POST",
data: model,
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")"
}).fail(function (jqXHR, textStatus) {
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$("#div_mensaje").html(data.MsgError);
});
jqxhr2 = $.ajax({
type: "POST",
data: model,
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")"
}).fail(function (jqXHR, textStatus) {
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$("#div_mensaje").html(data.MsgError);
});
[HttpPost]
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin)
...
...
...
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin)
...
...
...
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)
Llamado Ajax
jqxhr2 = $.ajax({
}).fail(function (jqXHR, textStatus) {
if (data.MsgError == "Refinanciación contabilizada correctamente.") {
type: "GET",
data: $('form').serialize(),
dataType: "json",
url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")",
beforeSend: function () {
$.blockUI({
message: 'Espere por favor...',
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: 0.5,
color: '#fff'
}
});
}
$.unblockUI();
$("#arrendContent").html(jqXHR.responseText);
}).success(function (data) {
$.unblockUI();
$("#div_mensaje").html(data.MsgError);
$("#btn_contabilizar").attr("disabled", "disabled");
$("#btn_calcular").attr("disabled", "disabled");
}
});
Cuando se actualizan los datos del modelo en el controller los cambios no se reflejan en la vista
Problema:
Cuando en un action de un controller se modifican datos del modelo y se hace el return View, en la vista no aparecen actualizados dichos datos.
Solución:
Es necesario hacer ModelState.Remove("nombre-del-atributo")
Por ejemplo:
public ActionResult Prueba(ElModelo m)
{
m.Nombre = "el nuevo nombre";
ModelState.Remove("Nombre");
}
Suscribirse a:
Entradas (Atom)
