具有多个参数的MVC.Net控制器路径

时间:2016-09-13 05:10:17

标签: c# asp.net-mvc-4

[Route("add/user/{name}&{state}&{zipcode}&{indeFlag}&{email}")]     
public async Task<ActionResult> CreateUser(
                 string name,
                 string state,
                 string zipcode,
                 Boolean indeFlag,
                 string email)
{
}

如何在上面的示例中定义控制器方法的路径,以便将正确的数据传递给方法?

请帮忙。

1 个答案:

答案 0 :(得分:0)

你可以像这样传递每个参数:

[Route("[controller]")]
public class UserController : Controller
{

     // < MVC 6 :

     [Route("add")] 
     [HttpPost]    
     public async Task<IActionResult> Create(
                 string name,
                 string state,
                 string zipcode,
                 bool indeFlag,
                 string email)
     {
         // Your code here
     }

     // If you want call this in a simple get query
     [Route("quickadd")] 
     [HttpGet]    
     public async Task<IActionResult> Create(
                 string name,
                 string state,
                 string zipcode,
                 bool indeFlag,
                 string email)
     {
         // Your code here
     }

     // MVC 6 :

     [Route("add")] 
     [HttpPost]    
     public async Task<IActionResult> Create(
                 [FromForm]string name,
                 [FromForm]string state,
                 [FromForm]string zipcode,
                 [FromForm]bool indeFlag,
                 [FromForm]string email)
     {
         // Your code here
     }

     // If you want call this in a simple get query
     [Route("quickadd")] 
     [HttpGet]    
     public async Task<IActionResult> QuickAdd(
                 [FromQuery]string name,
                 [FromQuery]string state,
                 [FromQuery]string zipcode,
                 [FromQuery]bool indeFlag,
                 [FromQuery]string email)
     {
         // Your code here
     }

}

网址将是&#39; / user / add&#39;表格中的数据。

顺便提一下,其他解决方案是使用视图模型类,如下所示:

[Route("[controller]")]
public class UserController : Controller
{

     [Route("add")] 
     [HttpPost]    
     public async Task<IActionResult> Create(
                 AddViewModel model)
     {
         if (ModelState.IsValid)
         {
              // Put your code to create user here
         }
         else
         {
              // Put your code for error here
         }
     }

}

视图模型允许您使用数据批注进行一些检查,例如必填字段或格式检查。

using System.ComponentModel.DataAnnotations;

public class AddViewModel
{
     [Required(ErrorMessage = "Please enter a name")]
     [Display(Name = "Username")]
     [DataType(DataType.Text)]
     public string Name { get; set; }

     public string State{ get; set; }

     [Required]
     [DataType(DataType.EmailAddress)]
     public string Email{ get; set; }

     [Required]
     [DataType(DataType.PhoneNumber)]
     public string PhoneNumber{ get; set; }

     public AddViewModel()
     {}
}