ViewModel没有绑定

时间:2013-09-13 17:04:03

标签: c# asp.net-mvc razor

我在stackoverflow上发现一堆关于数组和列表没有绑定但是我只有一个简单的视图模型有4个字符串而且帖子没有给我表单值:

视图模型:

public class ReferralNetworkSearchCriteria
{
    public string Email = "";
    public string FirstName = "";
    public string LastName = "";
    public string TaxSSN = "";
}

ReferralNetworkController:

public ActionResult Search()
{
    ReferralNetworkSearchCriteria criteria = new ReferralNetworkSearchCriteria();
    return View(criteria);
}

[HttpPost]
public ActionResult Search(ReferralNetworkSearchCriteria criteria)

{
    return View(criteria);
}

查看:

@using OurCompany.ViewModels
@model ReferralNetworkSearchCriteria

@{
    ViewBag.Title = "Search Referral Network";
}

<h2>Search Referral Network</h2>

@using(Html.BeginForm("Search","ReferralNetwork",FormMethod.Post))
{
<fieldset>
    <div class="row">
        <div class="large-4 column">
            <label>Email</label>            
            @Html.TextBox("Email")
        </div>
        <div class="large-4 column">
            <label>
                First Name</label>
            @Html.TextBox("FirstName")
        </div>
        <div class="large-4 column">
            <label>
                Last Name</label>
            @Html.TextBox("LastName")
        </div>
    </div>
    <div class="row">
        <div class="large-4 column">
            <label>SSN/Tax ID</label>
            @Html.TextBox("TaxSSN")
        </div>
    </div>
    <div class="row">
        <div class="large-2 column">
            @Html.ActionLink("Back", "Index", "ReferralNetwork", null, new { @class = "button", @style="width:100%"})
        </div>
        <div class="large-2 column">        
            <button style="width:100%">Search</button>
        </div>
    </div>
</fieldset>    
}

*编辑: 我还尝试将@Html.TextBoxFor(x => x.Email)用于所有文本输入,但帖子上仍然没有值。感谢

1 个答案:

答案 0 :(得分:5)

使用属性,而不是字段/变量,否则DataBinder根本不会绑定。我还建议尽可能使用@Html.TextBoxFor(x => x.Email)

public class ReferralNetworkSearchCriteria
{
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string TaxSSN { get; set; }
}