It's not clear if you're using MVC or Web API, but in either case, it would be a good idea to look at the following resources when considering how to use ModelState validation to validate form input:
The approaches are generally the same but with some variations.
Regarding your HTML stored in formPostText
, is there any reason you are building your form using a string? I would recommend using a view as doing so will better separate your presentation layer from your logic layer. If you must generate the raw HTML content, you can do something like this:
private string GetViewHtml(FormViewModel model)
{
return this.RenderView("/Views/Shared/FormView.cshtml", model);
}
In this example, which was built for MVC 5, RenderView
is an extension method of the controller:
public static class ControllerExtensions
{
public static string RenderView(this System.Web.Mvc.Controller controller, string viewName, object model)
{
return RenderView(controller, viewName, new ViewDataDictionary(model));
}
public static string RenderView(this System.Web.Mvc.Controller controller, string viewName, ViewDataDictionary viewData)
{
var controllerContext = controller.ControllerContext;
var viewResult = ViewEngines.Engines.FindView(controllerContext, viewName, null);
StringWriter stringWriter;
using (stringWriter = new StringWriter())
{
var viewContext = new ViewContext(
controllerContext,
viewResult.View,
viewData,
controllerContext.Controller.TempData,
stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
}
return stringWriter.ToString();
}
}