Can't pull data out of ViewBag in MVC

£可爱£侵袭症+ 提交于 2020-01-14 14:27:27

问题


I'm trying to pull data out of ViewBag and to insert it into a form hidden field via JS, before submit.

It doesn't work.

While debug, I find that part of the JS expression is kind of ignored, and as a result, a 'var' is evaluated to an empty string.

Here's the JS part, which supposed to do the assignment:

function setid() {
   var id = '@(ViewBag.id)';
   $('#idField').val(id);
};

in debug I get the below expression, which of course leads to a null 'id':

function setid() {
    var id = '';
    $('#idField').val(id);
  };

(I'm not sure it's the only obstacle)

This JS function is being called by a 'OnBegin' argument of 'Ajax.BeginForm' on the same page.

This's the html hidden field that resides within the form, which into I'm trying to assign the 'id' value:

input type  ="hidden" name ="id" id ="idField" value ="" 

and the following is the Controller, which returns a Partial, that is rendered as a jquery dialog:

public ActionResult openDialog()
    {
        ViewBag.id = TempData["id"];
        return PartialView("EndLoadDetailsDialog");
    }

Updated: As I think of it, I might have found the problem. Please let me know if I'm right:

The controller in which I define the viewbag value, returns a partial view, which is the last view that is beinng returned.

This partial view is rendered to a JQuery dialog. After I close it, I return to the one before, which contains a form. In the form view (the one before the last one) I'm trying to access the viewbag value via JS function, and assign it to a hidden field in the form. So actually, I'm trying to get the viewbag value, not from the view to which I've sent the viewbag.

Is it a problem? Are viewbag values available only from the last view that has rendered?

来源:https://stackoverflow.com/questions/10269975/cant-pull-data-out-of-viewbag-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!