Using named parameters as controller input compared to FormCollection

I am new to ASP.NET MVC, so this may have an obvious answer. Right now I have a form in my view with a lot of input controls, so I have an action that looks like this:

public ActionResult MyAction(string formItemOne, int? formItemTwo, etc...)

It has a dozen options, which is pretty ugly. I am trying to change it to this:

public ActionResult MyAction(FormCollection formItems)

and then analyze the elements dynamically. But when I go to FormCollection, form elements no longer "automatically" remember their values ​​via postback. Why does a change in FormCollection change this behavior? Anything simple I can do to make it work automatically again?

Thanks for the help,

~ Justin

+3
3

. :

class MyModel
{
  public string ItemOne { get; set; }
  public int? ItemTwo { get; set; }
}

:

public ActionResult MyAction(MyModel model)
{
  // Do things with model.

  return this.View(model);
}

:

<%@ Page Inherits="System.Web.Mvc.ViewPage<MyModel>" %>
<%= Html.TextBox("ItemOne", Model.ItemOne) %>
<%= Html.TextBox("ItemTwo", Model.ItemTwo) %>
+4

, . POST , , .

- . , - , :

public ActionResult MyAction(string formItemOne, int? formItemTwo, etc...)

public ActionResult MyAction(FormItems formItems)
{
  //your code...
  return View(formItems);
}

FormItems

public class FormItems
{
  public property string formItemOne {get; set;}
  public property int? formItemTwo {get; set;}
}

ASP.NET MV# 50 - .

+1

, , ModelState. .

If you use UpdateModel () or TryUpdateModel (), I think the values ​​will be saved.

0
source

Source: https://habr.com/ru/post/1721027/


All Articles