我的視圖中有一個 DropDownListFor,它從服務器上的日期串列中選擇一個日期。當我使用 jQuery .on "change" $.post 操作將我選擇的日期發布回控制器時,它會正確地從服務器獲取更新的資料值并更新視圖模型,但是它不會顯示在瀏覽器。它保留以前的值。但是,如果我單擊視圖表單中的提交按鈕,它會使用來自服務器的資料正確更新資料欄位。我如何發布下拉串列選擇決定了我的資料欄位是否正確更新。
有沒有人對我如何讓 jQuery 帖子更新視圖中的資料欄位而不是保留以前的值有任何建議?
這是我的視圖模型:
public class HtmlData
{
public string FileDateListSelection { get; set; }
public List<SelectListItem> FileDateList { get; set; }
public string ServerData { get; set; }
public HtmlData(string selectedDate, List<SelectListItem> fileDateList, string serverData)
{
FileDateListSelection = selectedDate;
FileDateList = fileDateList;
ServerData = serverData;
}
}
這是我的觀點:
@model MvcJqueryTest.Models.HtmlData
@using (Html.BeginForm("SubmitButtonDateChange", "Home", FormMethod.Post, new { id = "dateSelectionForm" }))
{
<div class="row">
<div class="col-md-4">
<div id="dateList">
@Html.DropDownListFor(m => m.FileDateListSelection, Model.FileDateList)
</div>
</div>
<div class="col-md-2">
<div id="buttons">
<input type="submit" name="submit" value="Fetch" id="fetchButton" />
<input type="submit" name="submit" value="Reset" id="resetButton" />
</div>
</div>
</div>
}
<div class="row">
<div class="col-md-8">
<br />
<h3>@Model.ServerData</h3>
<br />
</div>
</div>
<script type="text/javascript">
$('#FileDateListSelection').on("change", function () {
var menuDateSelected = $('#FileDateListSelection').val();
$.post(
'@Url.Action("JqueryDateChange", "Home")',
{ selectedDate: menuDateSelected },
function (response) {
}
);
});
</script>
這是我的家庭控制器方法:
public ActionResult Index(string dateString)
{
DateTime compareTime = DateTime.Today;
if (!string.IsNullOrEmpty(dateString))
compareTime = DateTime.Parse(dateString);
string quote = "Now is the winter of our discontent";
if (compareTime < DateTime.Today)
quote = "Made glorious summer by this sun of York";
string selectedDate = FileOperations.GetDateList(compareTime, out List<SelectListItem> dateList);
HtmlData hd = new HtmlData(selectedDate, dateList, quote);
return View(hd);
}
[HttpPost]
public ActionResult SubmitButtonDateChange(string FileDateListSelection, string submit)
{
string selectedDate = FileDateListSelection;
if (submit.Equals("Reset", StringComparison.OrdinalIgnoreCase))
selectedDate = DateTime.Now.Date.ToString("d", CultureInfo.GetCultureInfo("en-US"));
return RedirectToAction("Index", "Home", new { dateString = selectedDate });
}
[HttpPost]
public ActionResult JqueryDateChange(string selectedDate)
{
return RedirectToAction("Index", "Home", new { dateString = selectedDate });
}
The GetDateList method just returns a SelectListItem list of dates of files in a folder for the dropdown list, and selects one date as the selected item in the list. If the selected date is before today, the h3 tag containing the view model's "ServerData" property in the view shows "Now is the winter of our discontent". If the selected date is after midnight today, the h3 tag shows "Made glorious summer by this sun of York".
When I change the selection in the dropdown list, the JqueryDateChange controller method executes, and does a RedirectToAction to the Index method with the selected date as a parameter, which fills in the view model with the correct data for the "ServerData" property. But the "ServerData" value in the model is not displayed in the browser. It always retains the previous value, even though I can see the correct value there in the debugger when I set a break on <h3>@Model.ServerData</h3> in the view.
When I click the Fetch or Reset buttons in the view's form, the SubmitButtonDateChange controller method executes, and also does a RedirectToAction to the Index method with the selected date as a parameter. That also fills in the view model with the correct value for the "ServerData" property, but then it is correctly updated in the browser, showing the new value based on the dropdown list selection.
我最初使用 $.ajax 來發布新的下拉串列建議,但也有同樣的問題。我還嘗試在表單的大括號內移動“@Model.ServerData”,但這也無濟于事。我發現了一些我認為可能有幫助的關于 ModelState 的資訊,但是當我在除錯器中查看它時,它只有一個用于 dateString 引數的鍵/值對,所以我看不到如何使用它來解決問題。
uj5u.com熱心網友回復:
我認為AJAX解決方案足以滿足您的情況。您可以執行以下操作。
首先,id為您的 HTML 元素定義一個唯一的,您將在其中顯示 的值ServerData:
<div class="row">
<div class="col-md-8">
<br />
<h3 id="serverDataID">@Model.ServerData</h3>
<br />
</div>
</div>
然后你需要AJAX像這樣定義你的呼叫:
<script type="text/javascript">
$('#FileDateListSelection').on("change", function () {
var menuDateSelected = $('#FileDateListSelection').val();
var json = {
menuDateSelected: menuDateSelected
};
var options = {};
options.url = "@Url.Action("JqueryDateChange", "Home")";
options.type = "POST";
options.data = {"json": JSON.stringify(json)};
options.dataType = "json";
options.success = function (data) {
if (data.status == "true") {
$('#serverDataID').html(data.selectedDate);
}
else {
alert("Some Error");
}
};
options.error = function (data) {
alert("Error while calling function");
console.log(data);
};
$.ajax(options);
});
</script>
并且您的Controller方法將回傳 aJsonResult來處理回呼:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult JqueryDateChange(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var dateString = Convert.ToString(jsondata["menuDateSelected"]);
DateTime compareTime = DateTime.Today;
if (!string.IsNullOrEmpty(dateString))
compareTime = DateTime.Parse(dateString);
string quote = "Now is the winter of our discontent";
if (compareTime < DateTime.Today)
quote = "Made glorious summer by this sun of York";
string selectedDate = FileOperations.GetDateList(compareTime, out List<SelectListItem> dateList);
return Json(new { status = "true", data = selectedDate });
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/448316.html
標籤:C# jQuery asp.net-mvc
下一篇:計算作業日Jquery
