简体   繁体   English

从MVC4中的表单获取数据

[英]Getting data from a form in MVC4

In my view I have the following HTML, and yes I know I could use an HTML helper but in this case I cannot use that because of some scripting we use on the page causes serious problems when I allow MVC to create the textarea. 在我看来,我有以下HTML,是的,我知道我可以使用HTML帮助器,但在这种情况下我不能使用它,因为我允许MVC创建textarea时,我们在页面上使用的一些脚本会导致严重的问题。

@Html.TextBox("name", "", new {  @placeholder = "name", @class = "formElement", @id="name"})
<textarea id="message" placeholder="comments" class="formElement"></textarea>

Then in my Controller I have setup a very basic line to print out the name and message. 然后,在我的控制器中,我设置了一个非常基本的行以打印出名称和消息。

    [HttpPost]
    public ActionResult Form(MessageViewModel model)
    {
        return Content("Name: " + model.name + " Message: " + model.message);
    }

Name is accessible just fine because it is created with the HTML helper, but I cant access message, nothing is ever returned for it. 名称可以很好地访问,因为它是使用HTML帮助器创建的,但是我无法访问消息,因此没有返回任何内容。 Both name and message are defined in my ViewModel: 名称和消息都在我的ViewModel中定义:

    public string name { get; set; }
    public string message { get; set; }

How do I access the text that is in my message textarea? 如何访问消息文本区域中的文本?

You should add a "name" attribute for the textarea. 您应该为textarea添加“name”属性。 html elements are posted based on their names. html元素根据其名称发布。

<textarea id="message" name="message" placeholder="comments" class="formElement"></textarea>

In MVC ii is a good pratice to have a proper Model in a View and assign the Model properties to the desired controls such as the next example: 在MVC ii中,最好在视图中具有适当的Model并将Model属性分配给所需的控件,例如下一个示例:

@Html.TextAreaFor(m => Model.remark, 10, 5, new { style = "resize: none" })

The @Html.TextAreaFor will be rendered as: @Html.TextAreaFor将呈现为:

<textarea cols="5" id="remark" name="remark" rows="10" style="resize: none"></textarea>

and will allow a correct posting when the form is submitted and the Action in the Controller is called with the Model sent by the View. 并在提交表单和使用View发送的模型调用Controller中的Action时允许正确过帐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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