在 ASP.NET MVC 中:从 Razor 视图调用控制器操作方法的所有可能方法 [英] In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

查看:30
本文介绍了在 ASP.NET MVC 中:从 Razor 视图调用控制器操作方法的所有可能方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个非常基本的问题.

I know this is a pretty basic question over here.

但是你能告诉我所有可能的选项
从 Razor 视图调用 控制操作方法 [通常是任何服务器端例程] 并且,
在什么场景中最适用.

But could you tell me all possible options available to,
call a Control Action Method [generally any server side routine] from a Razor View and,
in what scenarios each are best applicable to be used in.

谢谢.

推荐答案

方法一:使用jQuery Ajax Get调用(部分页面更新).

Method 1 : Using jQuery Ajax Get call (partial page update).

适用于需要从数据库中检索 json 数据的情况.

Suitable for when you need to retrieve jSon data from database.

控制器的动作方法

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

人物类

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

方法 2: 使用 jQuery Ajax Post 调用(部分页面更新).

Method 2 : Using jQuery Ajax Post call (partial page update).

适用于需要将部分页面发布数据到数据库中.

Suitable for when you need to do partial page post data into database.

Post 方法也和上面一样,只是将 Action 方法上的 [HttpPost] 替换为 post 用于 jquery 方法.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

有关更多信息,请查看 在此处将 JSON 数据发布到 MVC 控制器

For more information check Posting JSON Data to MVC Controllers Here

方法 3: 作为表单发布方案(整页更新).

Method 3 : As a Form post scenario (full page update).

适用于需要将数据保存或更新到数据库中.

Suitable for when you need to save or update data into database.

查看

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

动作方法

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

方法 4: 作为表单获取方案(整页更新).

Method 4 : As a Form Get scenario (full page update).

适用于需要从数据库中获取数据时

Suitable for when you need to Get data from database

Get 方法也和上面一样,只是替换了 Action 方法的 [HttpGet] 和 View 的表单方法的 FormMethod.Get.

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

希望对你有帮助.

这篇关于在 ASP.NET MVC 中:从 Razor 视图调用控制器操作方法的所有可能方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆