Question

I have a user ID in viewBag I want to access the ViewBag inside my dialog box

<script>
    $(function () {
        $("#dialog").dialog({
            autoOpen: false,
            modal: true,
            width: 339,
            overlay: {
                backgroundColor: 'red',
                opacity: 0.5
            },
            show: {
                effect: "blind",
                duration: 500
            },
            hide: {
                effect: "explode",
                duration: 700
            }
        });
    });

    function OpenDialog()
    {
        $('#dialog').dialog("open");
    }
</script>

<div id="open" onclick="OpenDialog();">Click To Open</div>  

  @ViewBag.UserID
    <div id="dialog">   
            <table>
                <tr>
                    <td>User ID</td>
                    <td>@ViewBag.UserID</td>
                </tr>
                <tr>
                    <td>Comments</td>
                    <td>@Html.TextArea("CommentsTextBox")</td>
                </tr>
            </table>
            <div class="alignCenter"> 
                 <input type="submit" value="Add" /> 
                 <input type="button" value="Cancel" /> 
            </div>
    </div>
Was it helpful?

Solution

Your code should have worked but may be Jquery dialog changing dom element value for div <div id="dialog">

You can try following approach.

Keep UserId in hidden field.

<input type="hidden" id="userId" value="@ViewBag.UserID" />

Make placeholder for UserId inside <div id="dialog">

<div id="dialog">
    <table>
        <tr>
            <td>User ID</td>    
            <td><span id="dialogUserId"></span></td>
        </tr>
    </table>
</div>

Get UserId and assign form place holder on OpenDialog() event.

<script>
function OpenDialog()
    {
        $("#dialogUserId").val($("#userId").val()); //if this won't work try adding this line after dialog("open")
        $('#dialog').dialog("open");
    }
</script>

OTHER TIPS

if you just want to access your Model variables or ViewBag inside jquery, you can try the following way.

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

do one thing place your User id in normal java script variable and on document ready get place value to that by J query

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top