个性化阅读
专注于IT技术分析

asp.net mvc动作选择器

点击下载

本文概述

动作选择器是应用于控制器动作方法的属性。用于根据请求选择正确的操作方法进行调用。 MVC提供以下操作选择器属性:

  1. 动作名称
  2. 行为动词

动作名称

这个属性允许我们为动作方法指定一个不同的名称。当我们想用其他名称调用动作时,这很有用。

在这里,我们使用ActionName属性为索引操作方法应用不同的名称。控制器代码如下所示:

// MusicStoreController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
    public class MusicStoreController : Controller
    {
        [ActionName("store")]
        public ActionResult Index()
        {
            return View();
        }
    }
}

现在,我们需要在MusicStore文件夹中创建一个与ActionName相同的视图。因此,我们创建了一个具有以下代码的store.cshtml文件。

// store.cshtml

@{
    ViewBag.Title = "store";
}
<h2>Hello, This is Music store.</h2>

输出:

当以不同的名称“ store”调用动作时,将产生以下输出。


行为动词

ASP.NET MVC提供适用于操作方法的操作动词,并适用于HttpRequest方法。有各种ActionVerb,并在下面列出。

  • HttpPost
  • HttpGet
  • HttpPut
  • HttpDelete
  • HttpOptions
  • HttpPatch

ActionVerbs是控制器处理的http请求的名称。我们可以使用它来选择动作方法。

在以下示例中,我们尝试通过get请求访问索引操作,该操作仅可用于httpPost请求。控制器代码如下所示:

// MusicStoreController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationDemo.Controllers
{
    public class MusicStoreController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Welcome()
        {
            return View();
        }
    }
}

以下是MusicStoreController的索引文件。

// index.cshtml

<div class="jumbotron">
    <h2>Welcome to the music store.</h2>
</div>

输出:

调用index动作时,它将产生以下输出。

当我们对存储操作方法发出get请求时,它将生成错误消息。

赞(0)
未经允许不得转载:srcmini » asp.net mvc动作选择器

评论 抢沙发

评论前必须登录!