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
}
4

1 に答える 1

3

投稿で使用する理由はFormCollectionわかりませんが、WebFormsのバックグラウンドを持っている可能性があります。MVCでは、ビューとの間でデータを転送するためにViewModelsを使用する必要があります。

デフォルトRegisterでは、MVC 3アプリのメソッドは、RegisterビューでViewModelを使用します。単に投稿してください。実際、インターネットテンプレートの一部として知らなかった場合、デフォルトのアプリにはすでに作成されているアプリがあります。

標準のパターンは、ビューで使用するデータを表すViewModelを持つことです。たとえば、あなたの場合:

public class RegisterViewModel {

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

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

コントローラには、aGetとaの2つのアクションが含まれている必要がありますPostGetレンダリングによりビューがレンダリングされ、ユーザーがデータを入力できるようになります。ビューを送信すると、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をそれ自体にする特定のパターンがあり、そのパターンに対抗することは困難な場合があります。初心者の場合、最初に好ましいパターンと戦略を理解し、次に非常によく理解したら、ニーズを満たすために独自のカスタム戦略のいくつかを採用することが最善です。それまでに、システムを十分に理解して、何をどこで変更する必要があるかを理解する必要があります。

ハッピーコーディング!!

于 2012-06-09T11:51:29.550 に答える