将值从Javascript函数传递给MVC模型

时间:2013-12-04 10:10:17

标签: javascript asp.net-mvc

我有以下ViewModel:

namespace SimpleModel.ViewModels
{
    public class ClientSearch
    {
       public int Type { get; set; }
       public string String { get; set; }
    }
}

以下是HTML代码段:

<div id="clientSelect">
    <input type="radio" name="clientSelect" value="1" />Account Number<br />
    <input type="radio" name="clientSelect" value="2" />ID Number / Company Number<br />
    <input type="radio" name="clientSelect" value="3" />Surname / Company Name<br />
    @Html.EditorFor(model => model.String)
</div>

<p>
    <input type="submit" value="Search" onclick="clientSearch('clientSelect')" />
</p>

我有以下JavaScript函数:

<script type="text/javascript">
    function clientSearch(strGroupName) {
        var selectedValue = 0;
        var arrInputs = document.getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var oCurInput = arrInputs[i];
            if (oCurInput.type == "radio" && oCurInput.name == strGroupName && oCurInput.checked)
                selectedValue = oCurInput.value;
        }
     }
</script>

我需要在Javascript函数中使用 selectedValue 更新ClientSearch模型 类型 字段,以便我可以通过模型返回Controller进行处理。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

首先,这个对象不行,你不能拥有一个c#keyword属性

public class ClientSearch
{
   public int Type { get; set; }
   public string String { get; set; } // This right here is a reserved c# keyword
}

因此,将您的ClientSearch课改为

public class ClientSearch
{
   public int Type { get; set; }
   public string SearchString { get; set; }
}

然后您的视图将如下所示:

<div id="clientSelect">
    @Html.RadioButtonFor(x => x.Type, 1) @:AccountNumber<br/>
    @Html.RadioButtonFor(x => x.Type, 2) @:ID Number / Company Number<br/>
    @Html.RadioButtonFor(x => x.Type, 3) @:Surname / Company Name<br />
    @Html.TextBoxFor(model => model.SearchString)
</div>

<p>
    <input type="submit" value="Search" />
</p>

不需要javascript ...想象一下:)