ASP.NET MVC:如何“模型绑定”非HTML辅助元素 [英] ASP.NET MVC: How to 'model bind' a non html-helper element

查看:106
本文介绍了ASP.NET MVC:如何“模型绑定”非HTML辅助元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我一个方法(S),我可以绑定一个模式属性一个HTML元素,而无需使用HTML帮助创建?

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

在换句话说,以一个纯HTML元素,例如:<输入类型=文本/>

In other words to a plain html element such as: <input type="text" />

推荐答案

如果你指的是模型绑定时,它不需要帮手,但命名约定。助手只是使它很容易和简洁的创建HTML标记。

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.

您可以创建一个普通的HTML输入刚才设置的名称属性正确。默认的命名约定只是基于圆点,省略父级别实体的名称,但是从那里限定它。

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.

考虑这个控制器:

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);
     }
}

而这一模式:

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; }
}

您可以在HTML纯粹创建如下形式:

You could create the following form purely in HTML:

<form method="POST" action="MyController/Submit">
    <div><label>Some property</label><input type="text" name="SomeProperty" /></div>
    <div><label>Another property</label><input type="text" name="Nested.AnotherProperty" /></div>
    <button type="submit">Submit</button>
</form>

如果你想显示贴值(第二个提交过载),你的HTML将不得不进行修改渲染模型的属性。你会用剃刀语法把这个在视图中,在这种情况下,要求 Submit.cshtml

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
<form method="POST" action="MyController/Submit">
    <div><label>Some property</label><input type="text" name="SomeProperty" value="@Model.SomeProperty" /></div>
    <div><label>Another property</label><input type="text" name="Nested.AnotherProperty" value="@Model.Nested.SomeProperty" /></div>
    <button type="submit">Submit</button>
</form>

所以,也可以不帮手做,但你要尽可能多的使用它们越好。

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

这篇关于ASP.NET MVC:如何“模型绑定”非HTML辅助元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆