从JavaScript调用C#方法并返回一个字符串

时间:2019-10-10 09:17:05

标签: javascript c# asp.net-mvc

我正在尝试创建一个网页,以显示SQL Server中的表中的列。几列必须具有选择列表,并且几列的值必须根据所选项目而变化。 例如,我有一个名为Accounts的表,该表具有一个AccountNumberAccountName列。我希望网页上的AccountName单元格根据选择列表中的AccountNumber选择而改变。我尝试使用JavaScript和jQuery将AccountNumber传递给获取AccountName的C#方法,但是当我进行选择和调试时,我收到一条错误消息,指出该方法可以接收该参数。 t为空。

JavaScript

function getAccountNumber(x) {
        var selectedAccountNumber = document.getElementById(x.id).value;
        var isNumber = isNaN(selectedAccountNumber);
        if (!isNumber) {
            var accountNumber = parseInt(selectedAccountNumber, 10);
            var accountName = $.post('@Url.Action("GetAccountName", "Statements")', accountNumber);
            alert(accountName);
        }
    }

C#

public string GetAccountName(int ID)
{
    var item = db.Accounts.Where(acc => acc.AccountNumber == ID).Select(acc => acc.AccountName).Single();
    return item;
}

我不知道为什么它没有正确传递参数。

4 个答案:

答案 0 :(得分:1)

检查以下代码

[HttpPost]
public string GetAccountName(int ID)
{
  JavaScriptSerializer js = new JavaScriptSerializer();
  var item = db.Accounts.Where(acc => acc.AccountNumber == ID).Select(acc => acc.AccountName).Single();
  return js.Serialize(item.ToString());

}

var accountNumber = parseInt(selectedAccountNumber, 10);
var targetUrl= "@Url.Action("GetAccountName", "Statements")"+ "?ID=" + accountNumber;
$.post(targetUrl, function (data) {
  alert(data);
});

答案 1 :(得分:0)

我认为这段代码的问题是作为参数传递的对象,它必须是列表类型:


    $.post('@Url.Action("GetAccountName", "Statements")', {ID: accountNumber }, function(htmlexterno){
           $("#cargaexterna").html(htmlexterno);

答案 2 :(得分:0)

问题是:您不能!直接调用代码...。您需要调用一个端点。也就是公开代码c#的东西,通常是通过Web项目(MVC)完成的。您需要先解决如何暴露c#的问题,然后再使用Java脚本进行修改。

export const checkForAvailableAgent = (topicId, serviceUrl, serviceId) => {
    return new Promise((resolve, reject) => {
        const serviceInfo = new window.adiaLive.ServiceInfo({
          topicId: topicId, // set here the topicId which you want listen for
          OnError: e => {
            // react to error message (optional)
            console.log("error: ", e);

            reject(); // reject on failure
          },
          OnServiceStateChange: e => {
            if (e.ConnectedAdvisers > 0) {
              // there are advisers online for given topicId
              console.log("studio available");
              resolve(true); // resolve instead of return
            } else {
              console.log("studio not available");
              resolve(false);
            }
          }
        });
        serviceInfo.connect(serviceUrl, serviceId);
    }) 
};

useEffect(() => {
    checkForAvailableAgent(
      `sales_${i18n.language}`,
      "https://linktoserviceurl",
      "serviceid"
    ).then((agent) => { // then callback is called when the promise resolved
        console.log("studio available is: ", agent);
    }).catch(error => { // catch is called when promise got rejected
        console.log('An error happened');
    });

  }, []);

更新

JS

[ApiController]
[Route("[controller]")]
public class SomeNameController : ControllerBase
{
    public SomeNameController()
    {

    }

    [HttpPost]
    public string Get((int id)
    {
        return "cat";
    }
}

答案 3 :(得分:0)

我试图使它尽可能简单,即使用常规的JQuery函数和MVC控制器。

服务器端

 public ActionResult GetAccountName(string accountNumber)
 {
    return Content("Account name of " + accountNumber);
 }

客户端(脚本)

<script language="javascript">
    $(document).ready(function () {
        $(".accountnumbers").change(function () {
            var accountNumber = $(this).val();
            var labelToUpdate = $("#" + $(this).data("label"));

            console.log(labelToUpdate);

            $.ajax({
                url: '@Url.Action("GetAccountName", "Home")',
                data: { "accountNumber": accountNumber},
                success: function (data) {

                    labelToUpdate.html(data);
                }
            })

        })
    });
</script>

为简单起见,我使用了静态控件ID,如果您有多个帐号字段,则可以使其为动态控件。

客户端HTML

<table>
<tr>
    <td>
        Account Number
    </td>
    <td>
        Account Name
    </td>
</tr>
<tr>
    <td>
        <input type="text" id="txtAccountNumber_1" class="accountnumbers" data-label="lblAccountName_1" />
    </td>
    <td><label id="lblAccountName_1"></label></td>
</tr>
</table>