简体   繁体   中英

How to pre-populate form in ASP.NET MVC

In my case, I need a model for such a view:

@model EditFormApplication.Models.NewForm

@using (Html.BeginForm("EditForm", "Home", FormMethod.Post))
}
   @Html.EditorFor(model => model.Field)
   @Html.EditorFor(model => model.Field)
   @Html.EditorFor(model => model.Field)
   <input type="submit" value="save">
}

@Html.EditorFor(model => model.Field) may be much more, but they are all the same. I do not know what should be the model for this case:

namespace EditFormApplication.Models
{
   public class NewForm
   {
       public string Field { get; set; }
   }
}

I need to send the filled model to the Homecontroller . In the view can be an unlimited number of identical inputs.

Or better fill the model without using EditorFor() ?

In the controller i just need to get the filled model

[HttpPost]
public ActionResult EditForm (NewForm model)
{
  return View();
}

To pre-populate your form you need to set the model property value in GET method as follows:

[HttpGet]
public ActionResult EditForm()
{
   NewForm newForm = new NewForm()
   {
      Field = "Your pre-populate text"
   }
   return View(newForm);
}

Now "Your pre-populate text" will be shown in every @Html.EditorFor(model => model.Field) in the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM