2017-03-07 47 views
0

我是新来的MVC,不太了解它很好,所以请不要用一些硬性条款。MVC 5按钮操作

我有一个表单有2个输入和1个输入类型提交,我想做一个函数,检查这2个输入的值是否相同。如果索引在家里,我应该在Controller Home中写这个函数吗?

我该如何调用该特定功能,以及如何获取2个值(来自输入)。 我可以很容易地做到这一点在JavaScript中,但我需要做到这一点MVC,我还没有找到任何好的教程来学习这一点(所以如果你知道一个初学者请给我)。

+1

这是学习[模型验证(https://docs.microsoft的好地方。com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/added-validation-to-the-model),你可以编写一个属性来检查属性是否与另一个定义匹配属性。看看你自己的自定义模型验证属性 – maccettura

回答

2

首先,定义一个ViewModel其表示在所述控制器和视图(控制器经由Controller.View(Object model)方法把它传递给视图,视图经由<form>提交其传递回给控制器)​​之间交换的数据。

你的情况:

class HomeViewModel { 

    public String FirstValue { get; set; } 

    public String SecondValue { get; set; } 

    public String Message { get; set; } 
} 

你的剃须刀.cshtml应该是这样的:

@model HomeViewModel 

<p>@(this.Model.Message)</p> 

using(Html.BeginForm()) { 

    <div> 
     @Html.LabelFor(m => m.FirstValue) 
     @Html.TextBoxFor(m => m.FirstValue) 
    </div> 

    <div> 
     @Html.LabelFor(m => m.SecondValue) 
     @Html.TextBoxFor(m => m.SecondValue) 
    </div> 

    <button type="submit">Submit form</button> 
} 

然后在你的控制器的POST动作/处理器可以应用自定义逻辑:

public class HomeController { 

    public ActionResult Index() { 

     return this.View(new HomeViewModel()); 
    } 

    [HttpPost] 
    public ActionResult Index(HomeViewModel model) { 

     if(model == null) return this.NotFound(); 

     if(model.FirstValue == model.SecondValue) { 
      model.Message = "Values match"; 
     } 
     else { 
      model.Message = "Values are different"; 
     } 

     return this.View(model); 
    } 
} 

请注意,Message属性是一个w ay因为它从未由视图设置(因为它不通过任何<input />元素进行维护)。

有些人,包括我自己,都觉得单向数据不应该在ViewModel而应是ViewData集合中,如果这样的话做这样的:

 if(model.FirstValue == model.SecondValue) { 
      this.ViewData["message"] = "Values match"; 
     } 
     else { 
      this.ViewData["message"] = "Values are different"; 
     } 

     // 

     <p>@(this.ViewData["message"])</p> 

注意ViewData只是一个字符串字典,而ViewModel是强类型的。有一个技巧可以获得强类型ViewData,但它有点复杂,我现在不会进入它。

正如你的问题的评论称,如果你的“值相等”的逻辑更关心的是验证比实际的业务逻辑,那么你使用很富裕内置的验证属性,最大限度地减少量的代码,你需要写:

[Compare("OtherPropertyName", ErrorMessage = "The values must match.")] 

您可能还需要添加[DisplayName][Required]太:

像这样:

class HomeViewModel { 

    [DisplayName("First value")] 
    [Required] 
    public String FirstValue { get; set; } 

    [DisplayName("Second value")] 
    [Required] 
    [Compare(nameof(this.FirstValue), ErrorMessage = "Second value must match First value.")] 
    public String SecondValue { get; set; } 
} 

而在你的看法:

<div> 
    @Html.LabelFor(m => m.FirstValue) 
    @Html.TextBoxFor(m => m.FirstValue) 
    @Html.ValidationMessageFor(m => m.FirstValue) 
</div> 

<div> 
    @Html.LabelFor(m => m.SecondValue) 
    @Html.TextBoxFor(m => m.SecondValue) 
    @Html.ValidationMessageFor(m => m.SecondValue) 
</div> 

而在你POST动作/处理器:

[HttpPost] 
public ActionResult Index(HomeViewModel model) { 

    if(!this.ModelState.IsValid) return this.View(model); 

    // ...