ASP.NET MVC: How to 'model bind' a non html-helper element

后端 未结 2 1705
轮回少年
轮回少年 2021-02-02 16:21

Could you tell me a way(s) that I can bind a model property to a html-element, created without using html helper?

In other words to a plain html element

2条回答
  •  佛祖请我去吃肉
    2021-02-02 16:43

    If you are referring to Model Binding, it does not require helpers, but naming convention. Helpers just make it easy and concise to create the HTML markup.

    You could create plain HTML inputs and just set the name attribute correctly. The default naming convention is just dot based, omitting the parent level entity's name, but qualifying it from there.

    Consider this controller:

    public class MyControllerController : Controller
    {
         public ActionResult Submit()
         {
             return View(new MyViewModel());
         }
    
         [HttpPost]
         public ActionResult Submit(MyViewModel model)
         {
                // model should be not null, with properties properly initialized from form values
                return View(model);
         }
    }
    

    And this model:

    public class MyNestedViewModel
    {
        public string AnotherProperty { get; set; }
    }
    
    public class MyViewModel
    {
        public MyViewModel()
        {
             Nested = new MyNestedViewModel();
        }
    
        public string SomeProperty { get; set; }
    
        public MyNestedViewModel Nested  { get; set; }
    }
    

    You could create the following form purely in HTML:

    If you want to display the posted values (in the second Submit overload), your HTML will have to be modified render the model properties. You'd place this in a view, in this case using Razor syntax and called Submit.cshtml:

    @model MyViewModel
    

    So, this can be done without helpers, but you'd want to use them as much as possible.

提交回复
热议问题