How to give a value for ViewBag inside the jquery in mvc, c#

I have following input field.

<input class="book_now_modal BClick" type="text" id="destinationFrom_modal" name="destinationFrom_modal" placeholder="@ViewBag.AmritsarList[0].Destination">

time to time I want to change the value inside the view bag.is there a way to give dynamic value to the viewbag item.I have tried with jquery as below.

  $(".AClick").click(function () {
            //$(".BClick").attr("placeholder"," ");
            var s = parseInt($(this).attr('id'));
            var neededVAl = "@@ViewBag.AmritsarList"+"["+s+"]"+".Destination";
            alert(neededVAl);
            var b = $(".BClick");
            $(this).attr("placeholder",neededVAl);
        });

like this I replace the placeholder as an alert it gives @ViewBag.AmritsarList[1].Destination but it didn't change the placeholder.how can I do that.

Answers 1

  • var neededVAl = "@@ViewBag.AmritsarList"+"["+s+"]"+".Destination";
    

    You can't access the ViewBag using above statement, since it accessible on server side. Your JavaScript statement is executed on the client side and can't directly access it.

    However, You can use Json.Encode Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format.

    var jsObject = @Html.Raw(Json.Encode(ViewBag.AmritsarList));    
    $(".AClick").click(function () {        
        var s = parseInt($(this).attr('id'));
        var neededVAl = jsObject[s].Destination;
        alert(neededVAl);
        $(this).attr("placeholder",neededVAl);
    });
    

Related Articles