Another solution would be to create a Viewmodel with attributes that should or should not be written:
namespace MyProject.ViewModels {
public class MyViewModel {
public int Prop1 { get; set; }
[Required]
public String Prop2 { get; set; }
public String Prop3 { get; set; }
public String Prop4 { get; set; }
...
public String Prop12 { get; set; }
}
}
Your View gets, instead of the Model itself, the filled Viewmodel:
@model MyProject.ViewModels.MyViewModel
...
Your Controller receives Viewmodel in the POST request and fills in a Viewmodel in GET:
public ActionResult Create()
{
var viewModel = new MyViewModel();
return View(viewModel);
}
//
// POST: /Cities/Create
[HttpPost]
public ActionResult Create(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
var model = new Model {
Prop1 = viewModel.Prop1,
Prop2 = viewModel.Prop2,
Prop3 = viewModel.Prop3,
...
Prop12 = viewModel.Prop12
};
context.Models.Add(model);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
How you are marking your optional fields?
– Leonel Sanches da Silva
For this specific case, I am not marking the optional and mandatory fields yet. I thought of creating a Fields class that would inform which of the 12 properties are required, and which are optional.
– Vinícius
I will post an answer. Let’s see if it will be useful.
– Leonel Sanches da Silva