繁体   English   中英

从javascript中将数据发送到mvc中的函数

[英]send a data from javascript in view to a function in mvc

我有一个包含1个函数的类。 如何从MyView中的javascript发送参数至此函数? 以及我如何获得回报价值。 我的课 :

public class CityClass { 
    public static long GetIdCountryWithCountryText(string countryy) 
    { 
        using (SportContext db = new SportContext())
        {
            return db.tbl_contry.FirstOrDefault(p => p.country== countryy).id;
        }
    }
}

如何从MyView中的javascript发送参数至此函数?

你根本做不到。 javascript对功能一无所知。 它不知道什么是C#或静态函数。 它不知道什么也不是ASP.NET MVC。

您可以使用javascript将AJAX请求发送到服务器端点,在ASP.NET MVC应用程序的情况下,该端点称为控制器动作 该控制器动作可以依次调用您的静态函数或其他任何函数。

因此,您可以执行以下控制器操作:

public ActionResult SomeAction(string country)
{
    // here you could call your static function and pass the country to it
    // and possibly return some results to the client.

    // For example:
    var result = CityClass.GetIdCountryWithCountryText(country);
    return Json(result, JsonRequestBehavior.AllowGet);
}

现在,您可以使用jQuery向此控制器操作发送AJAX请求,并将国家javascript变量传递给它:

var country = 'France';
$.ajax({
    url: '/somecontroller/someaction',
    data: { country: country },
    cache: false,
    type: 'GET',
    success: function(result) {
        // here you could handle the results returned from your controller action    
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM