模型:
public class From
{
public DateTime from { get; set; }
public DateTime to { get; set; }
}
控制器:
public MediaViewModel DashboardMediaByDate([FromBody] From y)
{ // some logic }
看法:
<script>
$(function () {
// Get value on button click and show alert
$("#myBtn").click(function () {
var from = {
from: $("#from").val(), to: $("#to").val()
};
alert(from.from);
var y = JSON.stringify(from);
$.ajax({
type: "POST",
data: y,
dataType: 'json',
url: "/Queues/DashboardMediaByDate",
contentType: "application/json"
}).done(function (res) {
alert(res);
});
});
});
</script>
當我從瀏覽器除錯請求時:
請求標頭 有效負載
我在 Controller 中收到的內容:
方法引數
如何將物件從視圖模型發送到控制器?
提前致謝,
uj5u.com熱心網友回復:
您可以根據需要使用以下AJAX呼叫來獲取您的資料:
AJAX:
<script>
$(function () {
// Get value on button click and show alert
$("#myBtn").click(function () {
var from = {
from: $("#from").val(), to: $("#to").val()
};
alert(from.from);
$.ajax({
type: "POST",
data: {'json': JSON.stringify(from)},
dataType: 'json',
url: "/Queues/DashboardMediaByDate"
}).done(function (res) {
alert(res);
});
});
});
</script>
你的Controller方法:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult DashboardMediaByDate(string json)
{
MediaViewModel myModel = new MediaViewModel();
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var from = Convert.ToDateTime(jsondata["from"]);
var to = Convert.ToDateTime(jsondata["to"]);
//Your logic
return Json(new {myModel=myModel});
}
與您的原始通話相比的更改:
contentType已從您的AJAX通話中移除- 在您的方法上添加
[HttpPost]了屬性Controller - 洗掉
[FromBody]屬性以將您的資料作為JSON字串獲取 - 將您更改
data為發送JSON字串而不是Model
將資料作為JSON字串獲取后,您可以Model根據需要將其反序列化為您的結構。當我Model沒有很多屬性時,我通常使用這種方法。
You are using AJAX for your functionality which is generally used to update a portion of the page without reloading the entire page. If you want to redirect in the POST method from your Controller with a Model, then don't use ajax for your purpose. Alternatively if you know what to add to the view you return then handle the success callback and update the DOM.
You can access the above Model in your success method inside your AJAX like this:
success: function(data) {
//Get your model here
console.log(data.myModel);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/441186.html
標籤:C# jQuery 阿贾克斯 asp.net-mvc 模型视图控制器
上一篇:如何檢查第二個孩子是否存在
