简体   繁体   English

如何将 Ajax 与 MVC、MySQL 和实体框架一起使用,没有 razor 页面

[英]How to use Ajax with MVC, MySQL and Entity Framework, no razor pages

I messed up last time so let us see if I can get it right this time.我上次搞砸了,所以让我们看看这次我能不能把它弄好。 I am trying to figure out first where to put the Ajax at and how to put it in my controller.我想首先弄清楚 Ajax 的放置位置以及如何将其放置在我的 controller 中。 First my controller looks like this [update] I am trying to make my messages popup without refreshing.首先我的 controller 看起来像这样 [更新] 我试图让我的消息弹出而不刷新。 It works without ajax I just need someone to explain where to put in the ajax and how to interact with it.它可以在没有 ajax 的情况下工作我只需要有人解释在哪里放置 ajax 以及如何与之交互。 I don't want a alert I want the messages to update in that one section.我不想要警报,我希望在该部分中更新消息。 In the answer I tried to figure out what he was saying yet this is what i got when I clicked send在答案中,我试图弄清楚他在说什么,但这就是我点击发送时得到的

{"htmlMsg":"data addes to database successfull","htmlBody":"","success":true}

I don't want to see this I want it to just update the message section.我不想看到这个我希望它只是更新消息部分。 My goal has not been met yet so I am completely confused.我的目标还没有实现,所以我完全糊涂了。

Underneath you see the image of it working before I added the ajax recommended.在我添加推荐的 ajax 之前,您会在下面看到它工作的图像。 Now it sends me to that a different page.现在它把我送到了另一个页面。

它在没有 ajax 的情况下工作,但我如何获得发送按钮来添加消息

[HttpGet("wall")]
        public IActionResult Wall(int userID)
        {
            ViewBag.User = GetUserInDB();
            // if(ViewBag.User == null)
            // {
            //     return RedirectToAction("Index");
            // }
            ViewBag.Messages = DBContext.Messages
                                .Include(i => i.Messenger)
                                .ToList();
            return View();
        }

        [HttpPost("NewMessage/Add")]
        public IActionResult NewMessage( Message newMessage)
        {

            User userInDB = GetUserInDB();
            Message thisMessage = newMessage;
            System.Console.WriteLine(newMessage.TheMessage);
            thisMessage.UserID = userInDB.UserID;
           
            DBContext.Messages.Add(thisMessage);
            DBContext.SaveChanges();
            return RedirectToAction("Wall");
        }

What I am trying to do is change the outline to it because I know I need to do something like this我想要做的是将大纲更改为它,因为我知道我需要做这样的事情

[HttpPost("NewMessage/Add")]
        public JsonResult NewMessage( Message newMessage)
        {

            User userInDB = GetUserInDB();
            Message thisMessage = newMessage;
            thisMessage.UserID = userInDB.UserID;
           
            DBContext.Messages.Add(thisMessage);
            DBContext.SaveChanges();

            return Json(thisMessage);
        }

Is this correct?这个对吗? Or do I need to do something else?还是我需要做其他事情?

Secondly I truly can't figure out the second part on the HTML section.其次,我真的无法弄清楚 HTML 部分的第二部分。 Originally I had本来我有

@model Message

<div class="jumbotron p-2 m-3">
    <a href="/"><img class="logo" src="/images/melysLogo.jpg" alt="Logo Image"> </a>


    @if (ViewBag.User == null)
    {
        <a class="mr-2" href="/LoginOrRegister">Login Or Register</a>
    }
    else
    {
        <a href="/logout">Logout</a> <span>|</span>
        <a href="/AddRecipe"> Add Recipe</a><span>|</span>
        <a class="mr-2" href="/">Dashboard</a>
    }
     <span style="font-size:x-large;">Melly's Underground Cuisine</span>
</div>
<style>
    .messageboard {
        width: 97%;
        height: 600px;
        background-color: black;
        color: white;
    }
</style>

<div class="messageboard m-3 p-3 rounded">
    <div class="m-3 p-3 sizeclass">
        @foreach (Message message in ViewBag.Messages)
        {   
            <div class="d-flex justify-content-around m-3 p-3 ">
                <div class="p-2 rounded  largeLabel border">@message.TheMessage </div>
                    <div class="p-2 rounded smallLabel border d-flex justify-content-center align-items-center">
                    @message.Messenger.FirstName
                </div>
            </div>
        }
    </div>
</div>
<footer class="m-4">
    @if (ViewBag.User != null)
    {
        <form asp-action="NewMessage" asp-controller="Home"  a method="post">
            <input class="form-control-lg inputLabel m-1 " asp-for="TheMessage">
            <button class="btn btn-outline-primary btn-warning m-2" type="submit">Send</button>
        </form>
    }
</footer>

I have tried but don't understand what goes in the success section.我已经尝试过,但不明白成功部分的内容。 I also don't know what class or should i make name or id up for the message itself in the data I tried this but am still lost我也不知道 class 是什么,或者我应该在数据中为消息本身命名或标识我试过这个但我还是迷路了

<script type="text/javascript">  
        $(function () {  
            $("#btnGet").click(function () {  
                $.ajax({  
                    type: "POST",  
                    url: "/Home/NewMessage",  
                    data: { "name": $(".messageboard").val() },  //I am also guessing the class is probably wrong as well
                    success: function (response) {  
                          //what do I put here is what I am confused about as well
                    },  
                    failure: function (response) {  
                          console.log(response.failure)
                    },  
                    error: function (response) {  
                       console.log(response.error);  
                   }  
                });  
            });  
        });  
    </script> 

I would love to also know if using vs code is not worth it for c# and .net core thank you so much sorry about my last question.我还想知道对于 c# 和 .net 核心是否不值得使用 vs 代码,谢谢你对我的最后一个问题感到非常抱歉。 I didn't follow the guidelines properly我没有正确遵循指南

1-Replace this code with your view code 1-用您的视图代码替换此代码

@model Message

    <div class="jumbotron p-2 m-3">
        <a href="/"><img class="logo" src="/images/melysLogo.jpg" alt="Logo Image"> </a>


        @if (ViewBag.User == null)
        {
            <a class="mr-2" href="/LoginOrRegister">Login Or Register</a>
        }
        else
        {
            <a href="/logout">Logout</a> <span>|</span>
            <a href="/AddRecipe"> Add Recipe</a><span>|</span>
            <a class="mr-2" href="/">Dashboard</a>
        }
         <span style="font-size:x-large;">Melly's Underground Cuisine</span>
    </div>
    <style>
        .messageboard {
            width: 97%;
            height: 600px;
            background-color: black;
            color: white;
        }
    </style>

    <div class="messageboard m-3 p-3 rounded">
        <div class="m-3 p-3 sizeclass">
            @foreach (Message message in ViewBag.Messages)
            {   
                <div class="d-flex justify-content-around m-3 p-3 ">
                    <div class="p-2 rounded  largeLabel border">@message.TheMessage </div>
                        <div class="p-2 rounded smallLabel border d-flex justify-content-center align-items-center">
                        @message.Messenger.FirstName
                    </div>
                </div>
            }
        </div>
    </div>
     <footer id="myFooter" class="m-4">
            @if (ViewBag.User != null)
            {
                <form name="myForm" asp-action="NewMessage" asp-controller="Home"  a method="post">
                    <input class="form-control-lg inputLabel m-1 " asp-for="TheMessage">
                    <button class="btn btn-outline-primary btn-warning m-2" type="submit">Send</button>
                </form>
            }
        </footer>
  <script>
     $("#myform").submit( function () {
            e.preventDefault(); //prevent default form submit    
            $.ajax({   
                type: "POST",
                data : $("#myForm").serialize(),
                cache: false,  
                url: "/Home/NewMessage",   
               success: function (result) {  
                    //what do I put here is what I am confused about as well
                    if(result.Succeess)
                    {
                        //do youy want work if success....
                    }
                    else
                    {
                        //do youy want work if failed....
                    }
               },
               error: function (result) {  
                    console.log(result.error);    
            });   
            return false;   
    });
  </script>

2-Create a class in your project called JsonData 2-在名为 JsonData 的项目中创建一个 class

public class JsonData
{
    public string HtmlMsg { get; set; }
    public string HtmlBody { get; set; }
    public bool Success { get; set; }
}

and your NewMessage Action in controller change to:并且您在 controller 中的 NewMessage 操作更改为:

[HttpPost("NewMessage/Add")]
public JsonResult NewMessage(Message newMessage)
{
  try
  {
     User userInDB = GetUserInDB();
     Message thisMessage = newMessage;
     thisMessage.UserID = userInDB.UserID;
           
     DBContext.Messages.Add(thisMessage);
     DBContext.SaveChanges();

     return Json(new JsonData()
     {
       HtmlMsg = "data add to database successfull",
       HtmlBody = "",
       Success = true,
     });
  }
  catch
  { 
      return Json(new JsonData()
     {
       HtmlMsg = "data add to database failed",
       HtmlBody = "",
       Success = false,
     });
  }

 
}

So I got it to work thank you a lot but this is what I did所以我让它工作非常感谢你,但这就是我所做的

// wall html
@model Message

<div id="theDamMessages">
    <partial name="MessagePartial" />
</div>

<footer class="m-4">
    @if (ViewBag.User != null)
    {
        <form id="myform" method="POST">
            <input id="inputey" class="form-control-lg inputLabel m-1 " asp-for="TheMessage">
            <button class="btn btn-outline-primary btn-warning m-2" type="submit">Send</button>
        </form>
    }
</footer>
<div>
    <script>
        $("#myform").submit(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                data: $("#myform").serialize(),
                cache: false,
                url: "/AddMessage",
                success: function (result) {
                    console.log(result)

                    $("#theDamMessages").html(result);

                    $("#myform")[0].reset();
                    var theheight = $(".messageboard")[0].scrollHeight;
                    $(".messageboard").scrollTop(theheight);
                },

                error: function (result) {
                    console.log(result);
                }

            })
        });
    </script>
</div>
     [HttpPost("AddMessage")]
        public IActionResult AddMessage(Message newMessage)
        {

            User userInDB = GetUserInDB();
            Message thisMessage = newMessage;
            System.Console.WriteLine(newMessage.TheMessage);
            thisMessage.UserID = userInDB.UserID;

            DBContext.Messages.Add(thisMessage);
            DBContext.SaveChanges();

            ViewBag.Messages = DBContext.Messages
                                .Include(i => i.Messenger)
                                .ToList();          

            return PartialView("MessagePartial");
        }
       
<div class="messageboard m-3 p-3 rounded">
    <div class="m-3 p-3 sizeclass">
        @foreach (Message message in ViewBag.Messages)
        {   
            <div class="d-flex justify-content-around m-3 p-3 ">
                <div class="p-2 rounded  largeLabel border">@message.TheMessage </div>
            
                <div class="p-2 rounded smallLabel border d-flex justify-content-center align-items-center">
                    @message.Messenger.FirstName
                </div>
            </div>
        }
    </div>
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 ASP.NET Core Razor Pages 项目的 _layout.cshtml 文件中使用 Razor 页面使用实体框架作为部分视图? - How to use Razor Page Using Entity Framework as a partial view in _layout.cshtml file in ASP.NET Core Razor Pages project? 使用 Razor Pages、AJAX 和 Entity Framework Core 添加新的子数据项 - Adding a new child data item with Razor Pages, AJAX and and Entity Framework Core 如何使用带有剃刀视图的实体框架(.edmx模型)为MVC4或MVC 5创建局部视图? - How can i create a Partial View for MVC4 or MVC 5 using Entity Framework (.edmx Model) with Razor Views? 在使用实体框架的MVC4 Intranet应用程序中无法在Razor语法中使用HtmlHelper - Unable to Use an HtmlHelper in Razor syntax in MVC4 Intranet App using Entity Framework ASP.Net Razor Entity Framework Null Reference Exception 使用 Ajax 时 - ASP.Net Razor Entity Framework Null Reference Exception when use Ajax 如何使用Entity Framework + Mysql(在控制台应用程序中) - How to use Entity Framework + Mysql (in console application) 如何在实体框架和Mysql中使用规范函数 - how to use canonical functions in Entity Framework and Mysql Razor Pages 实体框架数据库上下文不能执行命令 - Razor Pages Entity Framework Database Context Can't Do Commands 如何使用ASP.NET MVC剃须刀中的实体框架检查数据库中是否存在记录? - How to Check if record exist in database using Entity Framework in ASP.NET MVC razor? 在从 MVC Razor 页面发布 ajax 后丢失 Model - Losing Model after posting ajax form MVC Razor Pages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM