2012-06-09 42 views
2

如何在返回视图时保持相同的数据?如何在返回视图时保持相同的数据?

我试图把形式返回到视图,但它没有工作。

有没有什么好的和简单的方法来做到这一点?

[HttpPost] 
public ActionResult Register(FormCollection form) 
{ 
    string name = form["Name"].Trim(); 
    if (string.IsNullOrEmpty(name)) 
    { 
     TempData["TempData"] = "Please provide your name "; 
     return View(form); 
    } 

    string email = form["Email"].Trim(); 
    var isEmail = Regex.IsMatch(email, @"(\w+)@(\w+)\.(\w+)"); 
    if (!isEmail) 
    { 
     TempData["TempData"] = "Sorry, your email is not correct."; 
     return View(form); 
    } 

     //do some things 
} 
+0

只是好奇你为什么要使用FormCollection而不是ViewModel。它会让你的生活更容易,尤其是这个问题:-) –

+1

向我们展示渲染视图的动作,这样我们就可以根据你的代码给出正确的答案。这一切都取决于那种方法 –

+0

我也有同感。注册的GET方法如何?你在那里使用什么模型?为什么你不能在POST中使用同一个模型? –

回答

3

不知道为什么你会使用在后FormCollection,但也许你来自一个WebForms的背景。在MVC中,您应该使用ViewModels将数据传输到Views或从Views传输数据。

默认情况下,MVC 3应用程序中的Register方法在Register视图中使用ViewModel。你应该简单地发回。实际上,如果您不知道它是Internet模板的一部分,则默认应用程序已经为您创建了。

标准模式是让ViewModel代表您在View中使用的数据。例如,你的情况:

public class RegisterViewModel { 

    [Required] 
    public string Name { get; set; } 

    [Required] 
    [DataType(DataType.EmailAddress)] 
    [Display(Name = "Email address")] 
    public string Email { get; set; } 
} 

你的控制器应包含2个动作,一个GetPostGet呈现视图并为用户输入数据做好准备。在提交后查看Post行动然后被调用。视图将ViewModel发送到动作,然后该方法采取行动来验证和保存数据。

如果数据存在验证错误,将ViewModel返回到视图并显示错误消息非常简单。

这里是Get行动:

public ActionResult Register() { 
    var model = new RegisterViewModel(); 
    return View(model); 
} 

这里是Post行动:

[HttpPost] 
public ActionResult Register(RegisterViewModel model) { 
    if(ModelState.IsValid) { // this validates the data, if something was required, etc... 
     // save the data here 
    } 
    return View(model); // else, if the model had validation errors, this will re-render the same view with the original data 
} 

你的看法会是这个样子

@model RegisterViewModel 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.Name) 
    </div> 
    <div class="editor-field"> 
     @Html.TextBoxFor(model => model.Name) <br /> 
     @Html.ValidationMessageFor(model => model.Name) 
    </div> 
    <div class="editor-label"> 
     @Html.LabelFor(model => model.Email) 
    </div> 
    <div class="editor-field"> 
     @Html.TextBoxFor(model => model.Email) <br /> 
     @Html.ValidationMessageFor(model => model.Email) 
    </div> 
} 

使用其他策略来捕捉并将数据保存在MVC应用程序中是绝对有可能的一个非常可扩展的框架。但是有一个特定的模式可以使MVC发挥作用,并且与这种模式相互作用有时会证明很困难。对于初学者来说,最好首先了解首选的模式和策略,然后一旦理解得很好,就可以采用一些自己定制的策略来满足您的需求。那时你应该理解系统,以便知道你需要改变什么以及在哪里。

快乐编码!

+0

谢谢你的建议。 :) –

相关问题