【问题标题】:How to pass values from View to Controller method with javascript? in asp .net core如何使用 javascript 将值从 View 传递到 Controller 方法?在 asp .net 核心中
【发布时间】:2018-05-22 08:40:32
【问题描述】:

我有某种信使,它有一个并排的面板,我可以在其中查看我的所有联系人。我想要的是当我单击其中一个以将 电话号码Id 传递给我的 Controller 以发送消息并将其保存在数据库中。
Foreach 打印我所有的联系人:

@foreach (var contact in Model.Contacts)
                {
                    <div class="chatperson" onclick="get_contact_number(@contact.PhoneNumber , @contact.ContactId)">
                        <div class="namechat">
                            <div class="pname">
                                @contact.Name
                                <a asp-action="ContactDetails" asp-route-id="@contact.ContactId" class=" glyphicon glyphicon-info-sign"></a>
                                <a asp-action="EditContact" asp-route-id="@contact.ContactId" class=" glyphicon glyphicon-pencil "></a>
                            </div>
                            <div class="lastmsg">@contact.PhoneNumber </div>
                        </div>
                    </div>
                }


在 div 中,我使用了 JS 方法并在那里传递了值:

function get_contact_number(contactNumber, contactId) {
    @Model.PhoneNr = contactNumber;
    @Model.ContactId = contactId;
}

最后我想将这些值传递给我的控制器函数

 public IActionResult SendMessage(MessengerViewModel model, string phoneNumber, string message)
    {
        var CurrentUserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
        if (ModelState.IsValid)
        {
            var newMessage = new Message();

            newMessage.UserId = CurrentUserId;
            newMessage.ContactId = model.ContactId;
            newMessage.Body = model.MessageBody;
            newMessage.Date = DateTime.Now;
            newMessage.isDelivered = true;
            _messageService.AddMessage(newMessage);

            AtSmsSender smsSender = new AtSmsSender();
            message = model.MessageBody;
            phoneNumber = model.PhoneNr;
            smsSender.SendSms(phoneNumber, message);

            return RedirectToAction("Index", "Messenger");
        }
        else
        {
            return RedirectToAction("Index", "Messenger");
        }
    }

【问题讨论】:

  • 你需要了解 AJAX 请求
  • 为什么不直接使用链接?
  • @Model.PhoneNr = contactNumber; 似乎不太对劲。请注意,PhoneNr 值呈现在服务器端。
  • @StephenMuecke 因为没有人喜欢当您在聊天中发送消息时重新加载整个页面?
  • @vasily.sib,我同意,但请查看 OP 的代码 - 他们有 RedirectToAction(),这意味着他们想要重定向 :)

标签: javascript c# asp.net-core asp.net-core-mvc


【解决方案1】:

您可以从get_contact_number 函数进行ajax 调用。类似于下面的代码

$.ajax({
    type:'GET',
    url: '@Url.Action("ActionName", "ControllerName")',
    async:true,
    success:function(response){
        //Do Something With response object returned by your action
    }
});

【讨论】:

  • 如果您使用 jQuery 并在您的应用中正确安装它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2017-11-24
相关资源
最近更新 更多