.NET Core (3.0) MVC - 如何重定向到不同的视图/ .cshtml页面?


  1. 我有一个名为WxJS.cshtml的视图。我使用 JavaScript 来获取 JSON 数据。该 JSON 数据将发送到 Wx 控制器
  2. Wx 控制器操作 JSON 数据并使用 Twilio 收到一条短信 - 这清楚地表明代码正在此控制器中工作。

我提出的问题是如何让Wx控制器从WxJS.cshtml Razor视图重定向到Wx.cshtml Razor视图以显示该数据?

我在 Wx.chstml 页面上设置了一个断点 - 程序控制会进入该断点 - 据我所知,这是要命中的最后一个断点。也就是说,Wx.chstml页面不会加载浏览器继续显示WxJS.cshtml页面。

我错过了一些东西(可能很明显(,因为我几个小时一直在努力寻找解决方案:-(

提前谢谢你!! :-(WxJS剃刀视图

<!doctype html>
<title>Example</title>
<script>
var xhr = new XMLHttpRequest();
var url = "https://cors-anywhere.herokuapp.com/https://www.511virginia.org/data/geojson/icons.rwis.geojson";

xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var jsonData = JSON.parse(xhr.responseText);
showWeather(jsonData);
}
};
xhr.open("GET", url, true);
xhr.send();
function showWeather(data) {
var output = "<ul>";
var i;
for (var i in data.features) {
output += "<li>" + data.features[i].id  + "</li>";
}
output += "</ul>";
document.getElementById("wxList").innerHTML = output;

$.ajax({
url: '/Home/Wx/',
data: JSON.stringify(data),
type: 'POST',
traditional: true,
contentType: 'application/json',
success: function (data) {
$('#message').html("Success!");
}
});


}</script>

<div id="wxList"></div>
** Home WX Controller **
[HttpPost]
public IActionResult Wx([FromBody] RootObject data)
{

System.Net.WebClient client = new System.Net.WebClient();
List<ConcerningWeatherData> WxStatDataList = new List<ConcerningWeatherData>();

RootObjectItteration ObjItteratrion = new RootObjectItteration();
WxStatDataList = ObjItteratrion.ItterateThroughRootObjectSettingValues(data, WxStatDataList);
List<ConcerningWeatherData> SortedList = new List<ConcerningWeatherData>();
try
{
SortedList = WxStatDataList.OrderBy(o => o.indexId).ToList();
ViewBag.WxStatDataList = SortedList;
}
catch (Exception ex)
{ ex.ToString(); }


try
{
TwilioSendText SendText = new TwilioSendText();
string sendToUser = SendText.ParseThroughWhatWxToSendUser(SortedList);
TwilioSendText numbers = new TwilioSendText();
List<String> listOfPhoneNumbers = new List<String>();
listOfPhoneNumbers = numbers.listOfPhoneNumbersToSendTo(listOfPhoneNumbers);
// TURN TWILIO SEND TEXT ON OR OFF HERE:
SendText.sendTextMessages(sendToUser, listOfPhoneNumbers);
}
catch (Exception ex)
{ ex.ToString(); }

//return View();
return View("Wx", "Home");

//return View();
// return Redirect("https://localhost:5001/Home/Wx.cshtml");

}

我试图让控制器定向到 Wx.cshtml 的视图(我有一个相同的页面 Weather.cshtml,当我使用 .NET Core 填充 JSON 时,它会显示这个 Weather.cshtml 页面(再次,Twilio 向我发送了包含所有数据的文本,因此我知道 JSON 解析正在工作。

@{
ViewData["Title"] = "C-Ville West";@*Privacy Policywas Privacy.cshtml*@
}
@*<h1>@ViewData["Title"]</h1>*@
<p></p>
@* loop over viewbag object *@
@foreach (var x in ViewBag.WxStatDataList)
{
// wx station name & description
<b>@x.description @x.name</b> @Html.Raw("<font color=#A9A9A9>(") @x.id @Html.Raw(")</font><br />")

// check station for bad / dangerous weather
@*x.weather_station_has_potentially_dangerous_weather @Html.Raw("<br />")*@
@if (@x.weather_station_has_potentially_dangerous_weather == true)
{
// then output any potentially dangerous weather
@Html.Raw("<font color=#ff0000>")@x.weather_stations_potentially_dangerous_conditions @Html.Raw("</font><br />");
}
// visibility
if (x.dont_show_visibility == false)
{
if (@x.visibility_show_value == true && @x.visibility_at_onePointTwoMiles_message_showTF == false)
{
@x.visibility  @Html.Raw(" visibility<br />")
}
else if (@x.visibility_at_onePointTwoMiles_message_showTF = true)
{
@x.visibility_at_onePointTwoMiles_message @Html.Raw(" visibility<br />")
}
else
{
@x.visibility_inoperative.ToString() @Html.Raw("<br />")
}
}
else
{
@x.visibility_inoperative.ToString() @Html.Raw("<br />")
}
// air temp
if (x.dont_show_air_temperature ==false)
{
if (@x.air_temperature_show_value == true)
{
@x.air_temperature @Html.Raw("&#176; air temperature<br />")
}
else
{
@x.air_temperature_inoperative.ToString() @Html.Raw("<br />")
}
}
// surface temp
if (@x.dont_show_surface_temperature == false)
{
if (@x.surface_temperature_show_value == true)
{
@x.surface_temperature  @Html.Raw("&#176; surface temperature<br />")
}
else
{
@x.surface_temperature_inoperative.ToString() @Html.Raw("<br />")
}
}
// surface conditions
if (@x.dont_show_surface_condition == false)
{
@x.surface_condition @Html.Raw("<br />")
}
// dewpoint
if (@x.dewwpoint_temperature_show_value == true)
{
@x.dewpoint_temperature  @Html.Raw("&#176; dewpoint temperature<br />")
}
else
{
@x.dewpoint_temperature_inoperative @Html.Raw("<br />")
}
// relative humidity
if (@x.relative_humidity_show_value == true)
{
@x.relative_humidity @Html.Raw("&#8453: relative humidity<br />")
}
else
{
@x.relative_humidity_inoperative @Html.Raw("<br />")
}
// wind direction -- speed -- gusts to
if (@x.dont_show_wind == false)
{
@x.all_wind_data @Html.Raw("<br />")
}


}
@*measurements in disclaimer*@
Temperatures in Fahrenheit, windpeeds in MPH. @Html.Raw("<br />") 

也就是说,Wx.chstml页面不会加载浏览器继续显示WxJS.cshtml页面。

那是因为你使用了 ajax。Ajax 允许您在当前视图中显示返回数据。

  • 如果你想渲染Wx.cshtml,你可以将返回的html附加到 您当前的 WxJs.cshtml:

控制器:

[HttpPost]
public IActionResult Wx()
{
ViewBag.WxStatDataList = SortedList;
return View();
}

阿贾克斯:

<div id="test"></div>
<script>
$(function() {
$.ajax({
url: '/Home/Wx/',
type: 'POST',
//...
contentType: 'application/json',
success: function (data) {
$("#test").html(data);
}
});
});
  • 如果你真的想重定向到 Wx.cshtml,你需要使用 会话来存储由于 ViewBag 的生命周期而造成的数据:

1.控制器:

[HttpPost]
public void TestWx()
{
//...
var SortedList = WxStatDataList.OrderBy(o => o.indexId).ToList();
HttpContext.Session.SetObject("ComplexObject", SortedList);
//no need to return View()...
}
[HttpGet]
public IActionResult Wx()
{
ViewBag.WxStatDataList= HttpContext.Session.GetObject<List<ConcerningWeatherData>>("ComplexObject");
return View();
}

2.阿贾克斯:

<script>
$(function() {
$.ajax({
url: '/Home/TestWx/',  //change this
type: 'POST',
//..
contentType: 'application/json',
success: function (data) {
window.location.href = "/Home/Wx"; //redirect to Wx.cshtml
}
});
});    
</script>

3.会话扩展:

using System.Text.Json;
public static class SessionExtensions
{
public static void SetObject(this ISession session, string key, object value)
{
session.SetString(key, JsonSerializer.Serialize(value));
}
public static T GetObject<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonSerializer.Deserialize<T>(value);
}
}

4.在启动中注册会话.cs:

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{        
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
//...
}

相关内容

最新更新