asp.net mvc-使用Javascript获取mvc表单数据

asp.net mvc - Get MVC Form Data Using Javascript

本文关键字:mvc 表单 数据 获取 Javascript net mvc- 使用 asp      更新时间:2023-09-26

我使用MVC有以下表单:

@using (Html.BeginForm())
    {
        <div class="editor-label">
            @Html.LabelFor(m => m.Title)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(m => m.Title)
            @Html.ValidationMessageFor(m => m.Title)
        </div>
        <div class="editor-label">
            @Html.LabelFor(m => m.Description)
        </div>
        <div class="editor-field">
            @Html.TextAreaFor(m => m.Description)
            @Html.ValidationMessageFor(m => m.Description)
        </div>
         <div class="editor-label">
            @Html.LabelFor(m => m.Icon)
        </div>
        <div class="editor-field">
            @Html.RadioButtonFor(m => m.Icon, "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png", new { @checked = "checked" }) <img src="http://maps.google.com/mapfiles/ms/icons/red-pushpin.png" alt="red pusphin" />
            @Html.RadioButtonFor(model => model.Icon, "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png") <img src="http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png" alt="blue pushpin" />
        </div>
    }

如何使用javascript检索数据?

我尝试了以下操作,但似乎不起作用:

document.getElementsByName('Title').value;

尝试这个

document.getElementById('Title').value;

检查这个小提琴

http://dotnetfiddle.net/t67Q3G

将所有控件的ID定义为:

@Html.LabelFor(m => m.Title,new{@ID="YOUR ID"})

按id获取值为:

$("#YOUR ID").val();

如果您需要从模型到javascript的值,您可以简单地执行此操作。

function showpopup()
{
   var model = @Html.Raw(Json.Encode(Model));
   alert(model.Title);
}