它是一个.aspnet core2网站。 我一直在做试验和错误'用不同的方法。
除了日期行之外,这些工作都没有,所以我知道razor正在工作。 我只想在代码中设置Userid的值,并将其显示为隐藏元素的值。没想到它会变得如此复杂。
Index.cshtml
@model iBasisMobileV14.Models.AccountViewModels.CheckoutViewModel
@using Microsoft.AspNetCore.Http.Authentication
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Identity
@using iBasisMobileV14.Models.AccountViewModels
.......
@DateTime.Now.Year //Works OK
@Model.UserID // Object reference not set to an instance of an object.
@Html.Raw(UserID);
@Html.HiddenFor(m => m.UserID , new { @id = "M_UserID" })
<input asp-for="UserID" id="M_UserID" />
CheckoutViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace iBasisMobileV14.Models.AccountViewModels
{
public class CheckoutViewModel
{
//[Display(Name = "UserID")]
private string _UserID;
public string UserID
{
get {
_UserID = "blabla";
return _UserID; }
set { _UserID = value; }
}
}
}
CheckoutController
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using NLog;
using Microsoft.AspNetCore.Identity;
using iBasisMobileV14;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using iBasisMobileV14.Models;
using iBasisMobileV14.Data.EntityModel;
using iBasisMobileV14.Classes;
namespace iBasisMobileV14.Controllers
{
public class CheckoutController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
IHttpContextAccessor _httpContextAccessor;
private AppSettings _appSettings { get; set; }
public string UserID { get; private set; }
public CheckoutController(
IHttpContextAccessor httpContextAccessor,
UserManager<ApplicationUser> userManager,
IOptions<AppSettings> appSettings)
{
_userManager = userManager;
_appSettings = appSettings.Value;
_httpContextAccessor = httpContextAccessor;
//Session needs something set or it changes every page load
UserID = "ccccccccc";
}
public IActionResult Index()
{
Guid userId = new Guid(_userManager.GetUserId(_httpContextAccessor.HttpContext.User));
ViewData["UserID"] = "sdfdsfdfsdfdsfd"; // userId;
// Logger.Info("Front");
return View();
}
}
}
答案 0 :(得分:1)
首先,您的视图强烈输入CheckoutViewModel
的实例,并且在您的视图中,您正在访问UserID属性。但是在您的GET操作中,您没有向视图传递任何内容。因此,视图中Model
基本上为空。您不应该在NULL
上访问媒体资源/调用某个方法,但这是您在视图中执行此行@Model.UserID
时尝试执行的操作。
所以解决方法是,创建视图模型类的对象并将该对象传递给视图。
var vm=new CheckoutViewModel();
Guid userId = Guid.NewGuid(); // to do : Replace with your code to get a valid Guid
vm.UserID = userId.ToString();
return View(v);
在视图中,您可以使用输入标记帮助程序。
@model CheckoutViewModel
<input asp-for="UserID" type="hidden" />
但是这会生成一个隐藏的输入,其值为blabla
,因为这是您的get
部分属性返回的内容!除非您在生成属性值时没有做一些逻辑,否则不需要使用私有属性。您只需使用公共财产
public class CheckoutViewModel
{
public string UserID { set;get;}
}