在 MVC 视图中,根据键检索字典的值
Retrieve value of Dictionary based on key, in MVC view
我正在尝试使用以下语句从字典中获取基于键的值:
它只是抛出 NULL 引用异常,但我确实有一个键值对 "MyKey"
@Model.DictionaryTest["MyKey"]
我应该使用词典列表吗?如果是这样,你能给我从中检索的语句吗?
更新——
这是我作为模型传递的 class,在控制器中我正在填充字典。(我检查了值是否完整)
public class Dummy_PreHires_View_Model
{
public Dictionary<string, string> DictionaryTest { get; set; }
}
这是字典上的数据之一,如果这有帮助,我已经尝试使用图片上提到的密钥,仍然抛出 NULL 异常:
Dictionary data snap
我的控制器代码:
public ActionResult PreHires_Dummy()
{
ViewBag.PreHires_Dummy_class = "active";
Dummy_PreHires_View_Model dpvm = new Dummy_PreHires_View_Model();
Dummy_PreHires_Translate_Model dptm = new Dummy_PreHires_Translate_Model();
dpvm.DictionaryTest = dptm.GetTranslatedData();
return View(dpvm);
}
我写了一个示例here。希望对你有所帮助。
型号:
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace HelloWorldMvcApp {
public class SampleViewModel {
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
//See here for list of answers
public string Answer { get; set; }
public Dictionary<string, string> DictionaryTest { get; set; }
}
}
控制器:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp {
public class HomeController : Controller {
[HttpGet]
public ActionResult Index() {
SampleViewModel viewModel = new SampleViewModel();
viewModel.DictionaryTest = new Dictionary<string, string>();
viewModel.DictionaryTest.Add("key1", "value1");
viewModel.DictionaryTest.Add("key2", "value2");
return View(viewModel);
}
[HttpPost]
public JsonResult GetAnswer(string question) {
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(answer);
}
private static Random _rnd = new Random();
private static List<string> _db = new List<string> { "Yes", "No", "Definitely, yes", "I don't know", "Looks like, yes"} ;
}
}
查看:
@model HelloWorldMvcApp.SampleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(m => m.Question)
@Html.TextBoxFor(model => model.Question, new {@class="form-control"})
@Html.ValidationMessageFor(model => model.Question)
@Model.DictionaryTest["key1"]
@Model.DictionaryTest["key2"]
</div>
<button type="button" class="btn btn-success submit">Ask</button>
}
<br/><br/>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function openAlert(txt) {
$('.alert-content').text(txt);
$('.alert').addClass('in');
}
function closeAlert() {
$('.alert').removeClass('in');
}
$(function(){
var answer = '@Model.Answer';
if(answer && answer != '')
openAlert(answer);
$('#Question').change(closeAlert);
$('#Question').keyup(closeAlert);
$('.submit').click(function(){
if($('form').valid()) {
$.ajax({
url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {Answer: '', Question: $('#Question').val()},
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp);
}});
}
else {
closeAlert();
}
});
});
</script>
</body>
</html>
我正在尝试使用以下语句从字典中获取基于键的值:
它只是抛出 NULL 引用异常,但我确实有一个键值对 "MyKey"
@Model.DictionaryTest["MyKey"]
我应该使用词典列表吗?如果是这样,你能给我从中检索的语句吗?
更新—— 这是我作为模型传递的 class,在控制器中我正在填充字典。(我检查了值是否完整)
public class Dummy_PreHires_View_Model
{
public Dictionary<string, string> DictionaryTest { get; set; }
}
这是字典上的数据之一,如果这有帮助,我已经尝试使用图片上提到的密钥,仍然抛出 NULL 异常: Dictionary data snap
我的控制器代码:
public ActionResult PreHires_Dummy()
{
ViewBag.PreHires_Dummy_class = "active";
Dummy_PreHires_View_Model dpvm = new Dummy_PreHires_View_Model();
Dummy_PreHires_Translate_Model dptm = new Dummy_PreHires_Translate_Model();
dpvm.DictionaryTest = dptm.GetTranslatedData();
return View(dpvm);
}
我写了一个示例here。希望对你有所帮助。
型号:
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace HelloWorldMvcApp {
public class SampleViewModel {
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
//See here for list of answers
public string Answer { get; set; }
public Dictionary<string, string> DictionaryTest { get; set; }
}
}
控制器:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp {
public class HomeController : Controller {
[HttpGet]
public ActionResult Index() {
SampleViewModel viewModel = new SampleViewModel();
viewModel.DictionaryTest = new Dictionary<string, string>();
viewModel.DictionaryTest.Add("key1", "value1");
viewModel.DictionaryTest.Add("key2", "value2");
return View(viewModel);
}
[HttpPost]
public JsonResult GetAnswer(string question) {
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(answer);
}
private static Random _rnd = new Random();
private static List<string> _db = new List<string> { "Yes", "No", "Definitely, yes", "I don't know", "Looks like, yes"} ;
}
}
查看:
@model HelloWorldMvcApp.SampleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>Hello Stranger</h1>
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(m => m.Question)
@Html.TextBoxFor(model => model.Question, new {@class="form-control"})
@Html.ValidationMessageFor(model => model.Question)
@Model.DictionaryTest["key1"]
@Model.DictionaryTest["key2"]
</div>
<button type="button" class="btn btn-success submit">Ask</button>
}
<br/><br/>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function openAlert(txt) {
$('.alert-content').text(txt);
$('.alert').addClass('in');
}
function closeAlert() {
$('.alert').removeClass('in');
}
$(function(){
var answer = '@Model.Answer';
if(answer && answer != '')
openAlert(answer);
$('#Question').change(closeAlert);
$('#Question').keyup(closeAlert);
$('.submit').click(function(){
if($('form').valid()) {
$.ajax({
url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {Answer: '', Question: $('#Question').val()},
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp);
}});
}
else {
closeAlert();
}
});
});
</script>
</body>
</html>