如何從控制器發回消息到視圖

[英]How to send back message from controller to view


I want to popup success or failure notification of form after form submission.

我希望在表單提交后彈出表單的成功或失敗通知。

I have a Partial View as _Appointment.cshtml with a form on it.

我有一個部分視圖作為_Appointment.cshtml,上面有一個表單。

I have one Main view Index on which i am loading it like this

我有一個主視圖索引,我正在加載它像這樣

@{Html.RenderPartial("~/Views/Appointments/_Appointment.cshtml", Model);}

In Controller i have

在控制器我有

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult _Appointment_public(Appointments appointments)
{
    if (ModelState.IsValid)
    {          
        db.Appointments.Add(appointments);
        db.SaveChanges();
        // return RedirectToAction("Index");
        ViewBag.Success = "Successfull";
        // RedirectToAction("../Home/Index");           
    }

    return Json(new {message = "Test" });
}

How do I pass and accept JSON Data to my view?

如何將JSON數據傳遞給我的視圖?

1 个解决方案

#1


0  

First of all, in your partial view you need JavaScript code to make an Ajax call (assuming you are using jQuery with MVC). https://api.jquery.com/jQuery.post/

首先,在您的局部視圖中,您需要JavaScript代碼來進行Ajax調用(假設您正在使用帶有MVC的jQuery)。 https://api.jquery.com/jQuery.post/

In your post action in your controller make sure you return Json data, as you are correctly doing. In the Success function in your JavaScript code, get the data and handle it as appropriate. You may want to return "true" or "false" and then do whatever you need to do. This could be from displaying a JavaScript alert to the user, to hiding the form's span/div and display another message instead.

在控制器中的post操作中,確保返回Json數據,正如您正確執行的那樣。在JavaScript代碼的Success函數中,獲取數據並根據需要進行處理。您可能想要返回“true”或“false”,然后執行您需要做的任何事情。這可以是向用戶顯示JavaScript警報,隱藏表單的span / div並顯示另一條消息。

If you need more complex data, you can also return that data from your controller and use jQuery to render that data in another div.

如果您需要更復雜的數據,還可以從控制器返回該數據,並使用jQuery在另一個div中呈現該數據。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/03/14/5f40de7037c696feffa441fb4fcea030.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com