开发者

Value set in the hidden field is not reflecting in document ready function

I am not able to retrieve the va开发者_运维问答lues from hidden field. Sometimes I am getting values & sometimes its coming empty. Please assist.

Also let me know can we store a C# arraylist in a hiddenfield? My HTML looks like this...

<input type="hidden" id="hdnSelectedContactID" value="@Model.Contact.ContactID" />
<input type="hidden" id="hdnSelectedAddressList" value="@Model.Contact.AddressList" />


$(document).ready(function () {
        _contactID = $("#hdnSelectedContactID").val();
        _addressList = $("#hdnSelectedAddressList").val();
}

After assigning a name to it in document.ready method, the outer html(in quick watch) appears like this...

outerHTML         "<INPUT id=hdnSelectedContactID type=hidden name=hdnSelectedContactID>"            String

outerHTML         "<INPUT id=hdnSelectedAddressList value=Dell.USP.Business.Models.TelephoneList type=hidden name=hdnSelectedAddressList>"       String


Why not use a helper to insert a hidden field?

@Html.HiddenFor(h => h.ContactID)

You can't store an arraylist in a hiddenfield as an object, but you can insert the values of an arraylist in a hiddenfield with delimiters to seperate them. You turn it into a string and load it in the view.


Addition: initialization of js-variable with ArrayList:

<script type="text/javascript">

    var _addressList = @Html.Raw(string.Format("['{0}']", string.Join("','", Model.Contact.AddressList.ToArray().Select(s => HttpUtility.HtmlEncode(s.ToString())))));

    $(document).ready(function () {

        // test 
        alert(_addressList[0]);
    });

</script>


As an extra note you CAN serialize your list into a hidden field using the MVCContrib Html.Serialize function. However this is basically for server side reuse again similar to viewstate


First of all in MVC 3.0, always try to use its own controls from HTML helpers, like @Html.HiddenFor(c => c.Contact.Title), instead of

<input type="hidden" id="hdnSelectedContactID" value="@Model.Contact.ContactID" />

Also I came to the conclusion that if there is another control with same lamda expression (For example my contactID & hidden contactID control both has the same h => h.ContactID expression), I ve to add an extra "id" attribute, as @Html.HiddenFor(h => h.Contact.Title, new { id = "hdnContactID" } ). Else wrong value might get overridden.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜