【问题标题】:C# Razor - Display comment where looped in value equals selectedIndex valueC# Razor - 显示循环值等于 selectedIndex 值的注释
【发布时间】:2015-10-26 17:58:39
【问题描述】:

我有一个如下所示的选择列表:

<select class="form-control">
     <option>Select</option>
     <option value="2">Order</option>
     <option value="5">Delivery</option>
     <option value="6">PickUp</option>
     <option value="13">Quote</option>
</select>

一旦用户选择了一个选项,我想仅在 db_Type = 所选选项的值时显示评论:

foreach (var note in Model.GetNotes)
    {
        <div class="current-note-container">
            <h5 class="note-comment"><b>Description:</b><br/> @note.db_Comment.Where(note.db_Type == /* Selected Index */)</h5>
        </div>
    }

我不太确定如何使用 razor 来完成这项工作,或者如何混合 javascript 来完成这项工作。

【问题讨论】:

  • 您使用的是哪个版本的 MVC?
  • 抱歉,应该添加标签 - MVC 4
  • 为什么不通过 JQuery 来做呢? C# 是服务器端脚本,而 JQuery 是为这些事情设计的客户端脚本
  • 我试图弄清楚如何使用 jQuery 来做这件事,但由于 @note.db_Type 来自我的模型,所以我无法弄清楚语法
  • 整数值有没有用?否则,您可以将评论保存在下拉值中

标签: javascript c# jquery asp.net-mvc razor


【解决方案1】:

这并不准确,但我认为您正在寻找类似的东西

<select class="form-control" onchange="GetComment(this.value)">
     <option>Select</option>
     <option value="2">Order</option>
     <option value="5">Delivery</option>
     <option value="6">PickUp</option>
     <option value="13">Quote</option>
</select>

将此添加到剃刀视图的脚本中

function GetComment(ID)
{
    var parameters = {};

    parameters["ListID"] = ID;

    $.ajax
    ({
        type: "GET",
        data: parameters,
        url: "/MyController/GetComment",
        success: function (message) {
            $('#note-comment').val(message);
        },
        error: function () {
            alert("error");
        }
    });
}

最后是你的控制器是这样的

[HttpGet]
public JsonResult GetComment(int ListID)
{
    return Json(Mylist[ListID].Comment);
}

【讨论】:

    【解决方案2】:

    Razor 是服务器端代码,因此您不能像您计划的那样将它与客户端脚本结合起来。

    改为使用 jQuery 监听 selection changed event 并将 (GET/POST) 新选择的值传回控制器和查询数据库并获取所需的注释。

    jQuery inside View(伪代码):

    $( "#ddlOptions" ).change(function() { //assuming ddlOptions is the Id of select list
        var selectedOptionId= $(this).val();             
        $.get('@Url.Action("ActionName","ControllerName")', { id: selectedOptionId}, 
          //You can use $.get(...) or $.post(...) based on action method type.
           function (data) {
              //Display/append the comment received to a container(div/span etc)
        });
    });
    

    控制器代码(伪代码)

    public JsonResult Get(int id)
    {
         //Query database here based on id to get the comment
         //e.g: db_comment.where(com=>com.id==id).FirstOrDefault();
    
         return Json(comment,JsonRequestBehavior.AllowGet);
    }
    

    希望这能给你一些想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 2013-04-06
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多