javascript参数通过id传递给方法

标签 javascript jquery asp.net-mvc

我正在 MVC 中构建一个 View ,其中选择一个连接到 sqlserver 的组合框,获取所选值并将其发送到 Controller 中的方法,但选择该值不会显示与所选值对应的数据表值。

代码:我的方法查询和该方法的使用是下一个:

    public List<Ciudades> GetCityById(int id)
     {
         List<Ciudades> lct2 = new List<Ciudades>();

         using (SqlCommand cmd = new SqlCommand())
         {
             string sql = string.Format("Select cityID,cityName from loccities where countryID={0}",id);
             cmd.Connection = con;
             cmd.CommandType = System.Data.CommandType.Text;
             cmd.CommandText =  sql;
             con.Open();
             SqlDataReader sdr = cmd.ExecuteReader();
             while (sdr.Read())
             {
                 Ciudades ct = new Ciudades();
                 ct.ID = Convert.ToInt32(sdr["cityID"]);
                 ct.Nombre = sdr["cityName"].ToString();
                 lct2.Add(ct);
             }
             return lct2;
         }
     }

Controller :

    [HttpPost]
    public JsonResult GetDataById(int id)
    {

        MvcSRDCBeta.Models.Ciudades obj = new MvcSRDCBeta.Models.Ciudades();
        var Respuesta = var1.GetCityById(id);
        return Json(Respuesta, JsonRequestBehavior.AllowGet);
    }

在 View 中,我有以下 javascript 代码,并且 $ .post ("GetDataById ($ _ POST ['code'])"行有问题

    <div class="form-group">
    <label for="id" class="col-md-2 control-label">Prueba C4</label>
    <div class="input-group">
        <span class="input-group-btn">
            <select class="form-control" name="optone" id="countrySel" size="1">
                <option value="">Select Countries</option>
            </select>
        </span>
        <span class="input-group-btn">
            <select class="form-control" name="opttwo" id="cities" size="1">
                <option value="">Selecciona cities</option>
            </select>
        </span>
        <span class="input-group-btn">
            <select class="form-control" name="optthree" id="regionSel" size="1">
                <option value="" selected="selected">Please select city first</option>
            </select>
        </span>
    </div>
</div>

我更改了加载页面中的js

function obtener_ciudades() {  //Funcion para obtener los estados de cada pais 
$("#countrySel").change(function () {
    $("#cities option").remove();
    $("#cities").append('<option value="">Selecciona Ciudades</option>');
    var datos = {
        //accion: "obtener_estados",
        codigo: $(this).val()
    }
    //console.log(datos);
    $.post("GetDataById($_POST['codigo'])", datos, function (datos) {
        console.log(datos);
        $.each(datos, function (key, value) {
            $("#cities").appendChild("<option value=" + value.ID + ">" + value.Nombre + "</option>");
        });
    }, "json");

});



 $(document).on("ready", inicio);

function inicio() { //inicializar funciones vitales para las paginas
    obtener_ciudades();
}

最佳答案

首先,您的地址不正确。您不需要在调用中使用 $_POST['codigo'] (看起来像某种 PHP 代码)。您需要的地址是/ControllerName/MethodName。只需更改

$.post("GetDataById($_POST['codigo'])", datos, function (datos) {

至(将 ControllerName 替换为实际 Controller 名称):

$.post("/ControllerName/GetDataById", datos, function (datos) {

接下来,由于您的方法 GetDataById 需要名为 Id 的单个参数,因此您需要提供一个具有属性 id 的对象,例如

$.post("/ControllerName/GetDataById", { id: $(this).val() }, function (datos) {

关于javascript参数通过id传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33057982/

相关文章:

javascript - 有没有办法触发调用另一个模块中存在 "might"的方法?

javascript - 从 JavaScript 中的触摸事件中排除滚动

javascript - 在 Javascript 中将两个 ImageData 混合成一个具有偏移量的 ImageData

javascript - 如何让按钮点击后凹陷?

asp.net-mvc - 如何最好地使用 ASP.NET MVC 中的 Expires header ?

asp.net-mvc - ASP.NET MVC : Prevent user from editing certain fields on the model

javascript - Html.BeginAjaxForm 从操作返回数据并将其注入(inject)到用户的 DOM 中

javascript - 意外的 token '<' React Webpack 构建

javascript - 检查一堆条件的更好方法

jQuery Isotope 添加自定义类并计算过滤项