Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

javascript - Call ViewBag in Jquery to get the value from controller

I am calling ViewBag.DeliveryDatebySupplier to update my textbox or just to alert. The value was always null. But when I debug and check the ViewBag in controller it has the date value.

Controller

if (ds.Tables[0].Rows.Count == 1)
{
    string dt = ds.Tables[0].Rows[0]["DeliveryDt"].ToString();
    DateTime myDate = Convert.ToDateTime(dt);
    dt =  myDate.ToString("yyyy-MM-dd");
    ViewBag.DeliveryDatebySupplier = dt.ToString();
    //Session["NewDeliveryDate"] = dt.ToString();                    
}

Jquery

function getDeliveryDateBySupplier() {
    var _storeID = $('#ddlStoreID :selected').val();
    var _SupplierID = $('#ddlSupplier :selected').val();

    var url = "@Url.Content("~/Home/DeliveryDatebySupplier")";

    $.ajax({
        data: {
             StoreID: _storeID,
             SupplierID: _SupplierID
        },
        type: 'POST',
        cache: false,
        dataType: 'json',
        url: url,
        success: function (result) {
            var newDeliveryDate = '@ViewBag.DeliveryDatebySupplier';
            alert(newDeliveryDate);
        },
        error: function (ex) {
            alert("Error getDeliveryDateBySupplier()");
        }
    });
}
question from:https://stackoverflow.com/questions/65648628/call-viewbag-in-jquery-to-get-the-value-from-controller

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming the action called DeliveryDatebySupplier in the HomeController is the method to set ViewBag.DeliveryDatebySupplier, then this will not work unfortunately.

The script will be generated when the full page was generated and at that time, the value would not have been set yet.

I would advise, rather than using the viewbag, return the value when DeliveryDatebySupplier is called in your script.

Controller will be something like this then

    if (ds.Tables[0].Rows.Count == 1)
    {
    string dt = ds.Tables[0].Rows[0]["DeliveryDt"].ToString();
    DateTime myDate = Convert.ToDateTime(dt);
    dt =  myDate.ToString("yyyy-MM-dd");
    return new JsonResult
    {
        data = new
        {
            DeliveryDatebySupplier = dt.ToString()
        }
    };                     
    }

and jquery would change to something like this

success: function (data) {
 if (data) {
    var newDeliveryDate = data.DeliveryDatebySupplier
    alert(newDeliveryDate);
}
else {
    //Error
}
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...