来自控制器的Ready ViewBag值?

时间:2017-01-04 13:49:58

标签: javascript c# jquery model-view-controller

在我的控制器中,我有以下ViewBag,它具有下拉列表的硬编码值

public ActionResult Order(string id, string printRequest)
{                            
this.ViewBag.PartialReasons = new List<string>() {" ", "Insufficient stock", "Suspended", "Retired", "Ordered Incorrectly", "Unable to deliver" };
}

我想要做的是,一旦从下拉列表中选择“无法交付”值,然后出现警告POP并显示“HELLO EVERYONE”,那么用户应该能够点击并保存,我现有的保存功能onclick在下面,

简而言之,只想从控制器视图中读取一个值。

    $('.pcss-save').click(function() {
        if (CheckSerialNumbersForQuantity()) {
            if (CheckReasons()) { //If Ordered incrrectly
                $('#genericmodal').find(".pcss-submit-genericmodal").unbind("click");
                $('#genericmodal').find(".modal-title").html("Confirmation");
                $('#genericmodal').find(".modal-body").html("This order will be Cancelled");
                $('#genericmodal').modal('show');
                $('#genericmodal').find(".pcss-submit-genericmodal").click(function() {
                    $("#orderform").submit();
                });
            } else {
                $("#orderform").submit();
            }
        }
    });

2 个答案:

答案 0 :(得分:0)

在您看来,您应该可以使用@ViewBag.PartialReasons直接调用ViewBag,当Razor引擎呈现脚本时,它将使用@ViewBag.PartialReasons中的这些值。

您可能想要做这样的事情。

    $('#yourDropDownID').on('change', function(){
        if(CheckReasons()){

          var genericModal = $('#genericmodal'); //Avoids rescanning the dom.
            genericModal.find(".pcss-submit-genericmodal").unbind("click");
            genericModal.find(".modal-title").html("Confirmation");
            genericModal.find(".modal-body").html("This order will be Cancelled");
            genericModal.modal('show');
            genericModal.find(".pcss-submit-genericmodal").click(function() {
                $("#orderform").submit();
        }
    });

你的检查原因可能是这样的。这是一种开放的解释。

function CheckReasons(){
    var myReason = @String.Join(ViewBag.PartialReasons.ToArray());

    //loop and figure it out if your reason is selected and return true or false
}

这一切都是我的头脑,所以可能需要一些调整,但这应该让你开始你想要做的事情。

UPDATE 您无法在浏览器中访问ViewBag,因为它只存在于服务器端。您需要渲染一个脚本,使用ViewBag在服务器上完成您想要的任务。 Razor引擎将填写C#代码的输出。

答案 1 :(得分:0)

首先提出一些问题:

  • 如何将Viewbag值加载到下拉列表中?
  • 您使用的是Razor视图吗?
  • 看来你提出了多个问题,所以我打算尝试点击每个问题。

通常下拉是键值对。使用Razor视图,您可以使用:

@Html.DropDownList("reasonListID", new SelectList(ViewBag.PartialReasons, "reasonCode", "reasonName"))

这假设viewbag对象是具有两个属性reasonCodereasonName的对象列表。

纯粹的字符串列表并不真正用于驱动逻辑,您希望将您的潜在价值编入代码,以便进行清晰易懂的比较。通过这种方式,您可以简单地查看reasonCode,而无需编码将您的选择值与“代码中可能没有多少意义的长字符串”进行比较,例如这可能在你的CheckReasons()函数中。

if CheckReasons() == "UD") {
   showModal( "HELLO EVERYONE");
}

更容易
if CheckReasons() == "Unable to deliver") {
   showModal("HELLO EVERYONE");
}

就弹出模态而言,看起来你正在使用jquery,所以看一下这个回答的问题:MVC3 Razor and Modal popup

相关问题