0
我試圖從一個對象視圖模型中獲取屬性,並將其屬性顯示在詳細信息視圖中。我試圖得到的屬性是sessionId,它在我的視圖中列出。我的代碼將其值取出不會返回正確的值,調試時,sessID的值爲0。我做錯了什麼?從ASP.Net中的「Details」視圖獲取模型屬性MVC
我的模型
public class SessionViewModel
{
public SessionViewModel()
{
}
public SessionViewModel(Session sessionDTO)
{
Id = sessionDTO.Id;
SessionTitle = sessionDTO.SessionTitle;
SessionDescription = sessionDTO.SessionDescription;
SessionPresenter = sessionDTO.SessionPresenter;
SessionLocation = sessionDTO.SessionLocation;
SessionRoom = sessionDTO.SessionRoom;
SessionDate = sessionDTO.SessionDate;
SessionOccupancy = sessionDTO.SessionOccupancy;
}
public int Id { get; set; }
public string SessionTitle { get; set; }
public string SessionDescription { get; set; }
public string SessionPresenter { get; set; }
public string SessionLocation { get; set; }
public string SessionRoom { get; set; }
public DateTime SessionDate { get; set; }
public int SessionOccupancy { get; set; }
public bool IsSelected { get; set; }
}
我查看
@model Project.Models.ViewModels.ManageSession.SessionViewModel
@{
ViewBag.Title = "SessionDetails";
}
<h2>Session Details</h2>
@using (Html.BeginForm("RegisterFromDetailsVM", "Session"))
{
<button type="submit" class="btn btn-success">Register</button>
<div>
<hr />
<dl class="dl-horizontal">
<dt>Session ID</dt>
<dd>
@Html.DisplayFor(model => model.Id)
</dd>
<dt>Title</dt>
<dd>
@Html.DisplayFor(model => model.SessionTitle)
</dd>
<dt>Description</dt>
<dd>
@Html.DisplayFor(model => model.SessionDescription)
</dd>
<dt>Presenter</dt>
<dd>
@Html.DisplayFor(model => model.SessionPresenter)
</dd>
<dt>Location</dt>
<dd>
@Html.DisplayFor(model => model.SessionLocation)
</dd>
<dt>Room</dt>
<dd>
@Html.DisplayFor(model => model.SessionRoom)
</dd>
<dt>Date</dt>
<dd>
@Html.DisplayFor(model => model.SessionDate)
</dd>
<dt>Occupancy</dt>
<dd>
@Html.DisplayFor(model => model.SessionOccupancy)
</dd>
</dl>
</div>
}
我的行動
[HttpPost]
public ActionResult RegisterFromDetailsVM(SessionViewModel sessionVM)
{
using (WSADDbContext context = new WSADDbContext())
{
//Capture logged in user info
int userID = context.Users.Where(x => x.Username == User.Identity.Name).Select(y => y.Id).FirstOrDefault();
string userName = context.Users.Where(x => x.Username == User.Identity.Name).Select(y => y.Username).FirstOrDefault();
string firstName = context.Users.Where(x => x.Username == User.Identity.Name).Select(y => y.FirstName).FirstOrDefault();
string lastName = context.Users.Where(x => x.Username == User.Identity.Name).Select(y => y.LastName).FirstOrDefault();
//Get the sessionId
int sessID = sessionVM.Id;
//Create the SubscribedSession DTO object
context.SubscribedSessions.Add(new SubscribedSession()
{
UserID = userID,
SessionID = sessID,
FirstName = firstName,
LastName = lastName,
Username = userName
});
//Save the changes
context.SaveChanges();
}
//return
return RedirectToAction("Index");
}
謝謝你Jasen。我結束了使用DisplayFor()和HiddenFor()。 DisplayFor()顯示這些值,而HiddenFor()實際上將這些值傳回給我的操作。 – tmt32mj