Neir0
Neir0

Reputation: 13367

Auto generate hidden inputs for all viewModel fields

Is it real to auto generate inputs for all hidden fields. I want something like this extestion method Html.AutoGenerateHiddenFor(viewmodel)

And output:

<input type="hidden" name="field1" value="123"  />
<input type="hidden" name="field2" value="1234" />
<input type="hidden" name="field3" value="1235" />

Upvotes: 0

Views: 1009

Answers (2)

Theo
Theo

Reputation: 81

public class ModelToPersistBetweenFormSubmits()
{
    public string field1 { get; set;}
    public string field2 { get; set;}
    public string field3 { get; set;}
    public string field4 { get; set;}
    public string GetHiddenFields(string excludeFields = "")
    {


            string[] excludeFieldList = excludeFields.Split(',');
            string val = string.Empty;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (System.Reflection.PropertyInfo property in this.GetType().GetProperties())
            {
                if (excludeFieldList.Contains(property.Name))
                {
                    continue;
                }
                else if (property.GetIndexParameters().Length > 0)
                {
                    val = string.Empty; //sb.Append("Indexed Property cannot be used");
                }

                else 
                {
                    val = (property.GetValue(this, null) ?? "").ToString();
                }
                sb.Append(string.Format("<input type='hidden' id='{0}' name='{0}' value='{1}'/>", property.Name, val));

                sb.Append(System.Environment.NewLine);
            }

            return sb.ToString();
        }
}



//render hidden fields except for current inputs

@Html.Raw(Model.GetHiddenFields("field4,field3"))

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You could use the MvcContrib's Html.Serialize method:

@using (Html.BeginForm())
{
    @Html.Serialize(Model)
    <button type="submit">OK</button>
}

and then inside your controller action that is receiving the postback:

[HttpPost]
public ActionResult SomeAction([Deserialize] MyViewModel model)
{
    ...
}

It uses classic WebForms's ViewState to serialize the model and emits a single hidden input field which will contain the serialized model. It kinda emulates the legacy ViewState.

An alternative solution would be to persist your model to your backend and then simply have a single hidden input field inside your form containing an unique id that will allow to retrieve the model back from this backend.

Upvotes: 1

Related Questions