Asp.net mvc 将源从字符串更改为JsonResult类型后读取ViewData

Asp.net mvc 将源从字符串更改为JsonResult类型后读取ViewData,asp.net-mvc,model-view-controller,viewdata,Asp.net Mvc,Model View Controller,Viewdata,以下代码已重构为: WorkItemModel model = new WorkItemModel(); ViewData["ServiceName"] = model.ServiceCatalogModels.First(s => s.Id == serviceId).Title; ViewData["ServiceName"] = GetServiceName(serviceId); public ActionResult GetServiceName(int serviceId)

以下代码已重构为:

WorkItemModel model = new WorkItemModel();
ViewData["ServiceName"] = model.ServiceCatalogModels.First(s => s.Id == serviceId).Title;
ViewData["ServiceName"] = GetServiceName(serviceId);

public ActionResult GetServiceName(int serviceId)
{
    WorkItemModel model = new WorkItemModel();
    return Json(model.ServiceCatalogModels.First(s => s.Id == serviceId).Title);
}
<input type="hidden" id="txtServiceName" value="@(ViewData["ServiceName"])" />
重构代码:

WorkItemModel model = new WorkItemModel();
ViewData["ServiceName"] = model.ServiceCatalogModels.First(s => s.Id == serviceId).Title;
ViewData["ServiceName"] = GetServiceName(serviceId);

public ActionResult GetServiceName(int serviceId)
{
    WorkItemModel model = new WorkItemModel();
    return Json(model.ServiceCatalogModels.First(s => s.Id == serviceId).Title);
}
<input type="hidden" id="txtServiceName" value="@(ViewData["ServiceName"])" />
这是ServiceName ViewData在其中一个视图中的使用方式:

WorkItemModel model = new WorkItemModel();
ViewData["ServiceName"] = model.ServiceCatalogModels.First(s => s.Id == serviceId).Title;
ViewData["ServiceName"] = GetServiceName(serviceId);

public ActionResult GetServiceName(int serviceId)
{
    WorkItemModel model = new WorkItemModel();
    return Json(model.ServiceCatalogModels.First(s => s.Id == serviceId).Title);
}
<input type="hidden" id="txtServiceName" value="@(ViewData["ServiceName"])" />

这是解决这个问题的正确方法,还是有办法通过将返回类型保留为ActionResult并返回JsonResult来解决这个问题?

我认为更改GetServiceName以返回字符串是正确的解决方案。实际上没有理由将其转换为JSON,因为MVC可以轻松地处理向模型传递字符串(当然还有更复杂的类型)的问题。在我看来,JSON应该在MVC中主要用于不涉及模型绑定器的异步调用

编辑:由于您是使用ViewData而不是实际模型将其传递给视图,因此(我认为)可以在视图中调用json反序列化器类来获取值,但实际上没有理由这样做。

您的“重构”代码没有任何意义。ViewData用于将模型中不存在的其他数据从控制器传递到视图。您不会将JsonResult分配给ViewData。我建议您在开始开发应用程序之前阅读更多关于MVC的内容。