MVC Razor按钮点击事件如何传递参数

11

我是MVC Razor的新手。

我有这个视图:

@model SuburbanCustPortal.Models.CustomerModel

@{
    ViewBag.Title = "Customer Summary";
}

<h2>Customer Summary Screen</h2>
<p>
    Please select an account below or add an existing account.
</p>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
  @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")

  <div>
    <fieldset>
      <legend>Existing Accounts</legend>

      @Html.Action("ExistingAccounts2")

      <p>
        <input type="submit" value="Add an Account" />
      </p>


    </fieldset>
  </div>
}

调用此方法的是哪个方法:

[Authorize]
public ActionResult ExistingAccounts2()
{
  return PartialView("ExistingAccounts", _client.RequestCustomersForAccount(User.Identity.Name));
}

这又调用了这个部分视图:

@model IEnumerable<SuburbanCustPortal.SuburbanService.CustomerData >

<br />
<br />
<table>

  @if (Model != null)
  {
    foreach (var usr in Model)
    {
      <tr>      
        <td>
          <input id="btnShowCustomer" name="btnShowCustomer2" type="submit" value="View"/>           
        </td>
        <td>
          @usr.AccountId
        </td>
        <td>
          @usr.Name
        </td>
@*        <td>
          @usr.DeliveryStreet
        </td>*@
      </tr>
    }
  }

</table>
<br />

最终显示如下:

enter image description here

到这一步为止,它已经可以正常工作。

我想做的是能够点击客户名称旁边的按钮来打开客户账户。

如何将该客户与按钮联系起来以知道应该打开哪个客户账户,并如何使按钮单击打开这个客户账户?

2个回答

10

点击按钮后,你需要将客户号码传回:

如果你在模型中有客户号码属性,你可以这样做:

<input id="btnShowCustomer" data-customerNumber="@usr.CustomerNumber" />
你可以使用@Html.ActionLink、@Ajax.ActionLink或jQuery,将数据作为POST请求发送到服务器: Action Link
@Html.ActionLink("LoadInfo", "Info", new {customerId=@usr.CustomerNumber})

jQuery

$("#btnShowCustomer").click(function() {

 var customerId = $("#btnShowCustomer").attr("data-customerNumber");
  $.ajax({ 
       type: "POST", 
       data: "customerId=" + customerId, 
       url: '@Url.Action("MyAction", "MyController")', 
       success: function (result) { 

       } 
 }); 

出现错误 -- “data-customerNumber 不是 input 元素的有效属性”。 - Nitin...
那我在控制器中如何获取这些信息呢? - Danieboy

0

我觉得这样应该可以解决问题!oid 应该是客户的 ID(我觉得路径不对 :))

@Ajax.RawActionLink("Action", "Controller", new { oid = '@Model.customerID'}, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "the view you want to show" }, new { id = "btnNewB", @class = "your btn class" })

祝你好运 ;)


无法解析符号“RawActionLink”。我该如何让它看到RawActionLink? - ErocM
嗯...这不应该发生...你得到了什么精确的错误信息? - Mihai Labo
在Visual Studio中确切的错误提示为:“无法解析符号“RawActionLink”。”。 - ErocM
嗯...这种事情从没发生过。我会研究一下的,但说实话我有点忙。要么你提一个新问题,要么使用达伦的答案,那也可以解决问题。希望能顺利解决。 - Mihai Labo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接