cfly24
cfly24

Reputation: 1962

Syntax error setting ViewBag to data attribute

I am trying to set ViewBag.OrderId to the value of the data attribute data-orderId, but I am getting a syntax error on the =:

@foreach (var order in Model.Orders)
{
<a class="btn-add-note" data-orderId="@order.db_OrderNo">Add</a>
}

JS:

$(".btn-add-note").click(function(){
    @ViewBag.OrderId = $(this).attr("data-orderId");
});

Anyone know why I am getting this syntax error?

Explanation:

The code shown here is in a partial view. Once clicked, it opens up a modal in it's parent view. The modal has a form in it that requires the selected orderId from the partial view. The orderId is then passed as a parameter into the controller on form submit. I have been having trouble figuring out the best way to do this so I was trying to just set ViewBag.OrderId to the value so I wouldn't have to try to pass it to the form first.

Let me know if that's confusing at all or if more details are needed.

Thanks!

Upvotes: 0

Views: 325

Answers (2)

JB06
JB06

Reputation: 1931

You can't mix server side and client side code.

What you can do however, is have a hidden field that you store your OrderId in, and then retrieve once you load your modal.

In your view add a hidden field

<input type="hidden" id="orderId" value="" />

Then just set it as you were trying to do with ViewBag

$(".btn-add-note").click(function(){
    $('#orderId').val($(this).attr("data-orderId"));
});

Now you can grab the OrderId from the hidden wherever you need it.


If you need the OrderId on the controller to load the form, just add a controller action for setting the ViewBag property

[HttpPost]
public void SetOrderId(string orderId)
{
    ViewBag.OrderId = orderId;
}

Then make your click event call this action instead

$(".btn-add-note").click(function(){
    $.ajax({
         url: '@Url.Action("SetOrderId", "ControllerName")',
         type: 'POST',
         data: { orderId = $(this).attr("data-orderId") }
    });
});

Upvotes: 0

Brian Mains
Brian Mains

Reputation: 50728

What you are trying to do will not work; @ViewBag.OrderID will have already rendered before that JS code works. You have to evaluate everything on the client, and if you need to access it on the server, store the value in a hidden field or send it to the server using AJAX.

Please provide some more info on what you are trying to do and we can help further.

Upvotes: 1

Related Questions