首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从javascript中将数据发送到mvc中的函数

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

Stack Overflow用户
提问于 2013-08-02 15:25:53
回答 1查看 93关注 0票数 0

我有一个包含1个函数的类。如何从myview中的javascript向此函数发送参数?以及如何获取返回值。我的班级:

代码语言: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;
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2013-08-02 15:29:16

如何从myview中的javascript向此函数发送参数?

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

您可以使用javascript向服务器端点发送AJAX请求,在ASP.NET MVC应用程序中,该服务器端点称为控制器操作。此控制器操作可以反过来调用您的静态函数或其他任何函数。

因此,您可以使用以下控制器操作:

代码语言:javascript
复制
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请求,并将country javascript变量传递给它:

代码语言: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    
    }
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18011136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档