Use two models in one form (view) - ASP.NET MVC - c#

In my form, which I created in a view, the user can press add or search.
If the "add" button is pressed, a different model should be used in the background than with the "search" option. The add model is validated but otherwise does not differ from the search model.
By clicking "search" the user shouldn't be forced to fill in all fields.
Code
Model - AddModel
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Name")]
[StringLength(200, MinimumLength = 1, ErrorMessage = "Not Allowed")]
public string Name { get; set; }
[Required]
[Display(Name = "Place")]
[RegularExpression(#"^[\w ]*$", ErrorMessage = "Not Allowed")]
public string Place { get; set; }
Model - SearchModel
public int Id { get; set; }
public string Name { get; set; }
public string Place{ get; set; }
Controller
[HttpPost, ValidateAntiForgeryToken]
public IActionResult Add(AddModel p) {
if (ModelState.IsValid) {
_ = InsertData(p);
ModelState.Clear();
return RedirectToAction("Add", new { Success = true });
}
return View();
}
public IActionResult Select(SearchModel p)
{
Task.WaitAll(SelectData(p));
return View(per); // per => list of selected data
}
View
#model **AddModel**
#if (ViewBag.success)
{
...
}
<form method="POST">
<div class="form-group">
#Html.LabelFor(m => m.Name, new { })
#Html.EditorFor(m => m.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.Name, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Place, new { })
#Html.EditorFor(m => m.Place, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m.Place, "", new { #class = "text-danger" })
</div>
<input asp-action="Add" type="submit" class="btn btn-outline-primary" value="Add" />
<input asp-action="Select" type="submit" class="btn btn-outline-success" value="Search" />
</form>
The AddModel is still used in the View, but I would like to specify in the controller which model I would like to use. So if you press "search" the SearchModel and with "add" the AddModel should be used. I've already tried it with dynamic, but then it came to problems with the #html helpers.
Does somebody has any idea?
Would appreciate ;)

I think what you are looking to do is called a ViewModel, this should help : https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3

Related

Multiple models in one view - login & register using ViewModel - with field & ModelState validation

I have a MVC 5 application that uses multiple models in one view for login & registration. A search on Google & Stack Overflow returns many examples on how to implement this. This example partially works. However, I'm having an issue with validation and I can't seem to find a clear example. If I click the login form without entering any values in the fields I always get a null reference and my ModelState is always valid!
My Login model:
public class LoginModel
{
[Required(ErrorMessage = "Please enter a valid username.")]
public string txtUsername { get; set; }
[Required(ErrorMessage = "The password field is required.")]
public string txtPassword { get; set; }
}
My Registration model:
public class RegisterModel
{
[Required(ErrorMessage = "Please enter a first name.")]
public string txtFirstName { get; set; }
[Required(ErrorMessage = "Please enter a last name.")]
public string txtLastName { get; set; }
}
My ViewModel:
public class ViewModelVM
{
public LoginModel loginModel { get; set; }
public RegisterModel registerModel { get; set; }
}
My Home Controller submit and register actions:
[HttpPost]
public ActionResult LoginSubmit(ViewModelVM vm)
{
if (ModelState.IsValid)
{
//perform other logic.
return View("Index");
}
else
{
return View("Login", vm.loginModel);
}
}
[HttpPost]
public ActionResult RegisterSubmit(ViewModelVM vm)
{
if (ModelState.IsValid)
{
return View("Index");
}
else
{
return View("Login", vm);
}
}
My View:
#model MVCTemplate.ViewModel.ViewModelVM
#{
ViewBag.Title = "Login & Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="col-lg-10 mx-auto">
#using (Html.BeginForm("LoginSubmit", "Home", FormMethod.Post))
{
<div id="loginForm" class="p-5">
<div class="form-group">
#Html.Label("Username", new { #class = "labeltiny" })
#Html.TextBox("txtUserName", "", new { #class = "form-control", #PlaceHolder = "Username" })
#Html.ValidationMessageFor(x => x.loginModel.txtUsername, "", new { #class = "text-danger labeltiny" })
</div>
<div class="form-group">
#Html.Label("Password", new { #class = "labeltiny" })
#Html.Password("txtPassword", "", new { #class = "form-control", #PlaceHolder = "Password" })
#Html.ValidationMessageFor(x => x.loginModel.txtPassword, "", new { #class = "text-danger labeltiny" })
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" name="btnLogin" id="btnLogin" tabindex="4" class="form-control btn btn-login" value="Log In" onclick="sweetalertSpinner()">
</div>
</div>
</div>
</div>
}
#using (Html.BeginForm("RegisterSubmit", "Home", FormMethod.Post))
{
<div id="registerForm" class="p-5" style="display: none">
<div class="form-group">
#Html.Label("First Name", new { #class = "labeltiny" })
#Html.TextBox("txtFirstName", "", new { #class = "form-control", #PlaceHolder = "Fist Name" })
#Html.ValidationMessageFor(x => x.registerModel.txtFirstName, "", new { #class = "text-danger labeltiny" })
</div>
<div class="form-group">
#Html.Label("Last Name", new { #class = "labeltiny" })
#Html.Password("txtLastName", "", new { #class = "form-control", #PlaceHolder = "Last Name" })
#Html.ValidationMessageFor(x => x.registerModel.txtLastName, "", new { #class = "text-danger labeltiny" })
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" name="btnRegister" id="btnRegister" tabindex="4" class="form-control btn btn-login" value="Register" onclick="sweetalertSpinner()">
</div>
</div>
</div>
</div>
}
</div>
As the docs says: "Model state represents errors that come from two subsystems: model binding and model validation."
The ModelState will represent one model only, and since you are defining the view model
public class ViewModelVM
{
public LoginModel loginModel { get; set; }
public RegisterModel registerModel { get; set; }
}
then model binding and model validation will be based on the attributes of ViewModelVM not the attributes within the objects of it and that's why you will get ModelState.IsValid == true
What I think you can use is the manual validation of each model, here you can find a way to do so.
Maybe you can create a class and inherit from the two models you want, but I'm not sure if this could work. Let us know in case you've tried it.
I found what appears to be the solution.
Add the following to the ViewModel
public class ViewModelVM
{
public LoginModel loginModel { get; set; }
public RegisterModel registerModel { get; set; }
public string txtUsername { get; set; }
public string txtPassword { get; set; }
public string txtFirstName { get; set; }
public string txtLastName { get; set; }
}
Change the View as follows for each form field (removing reference to loginModel and registerModel):
#Html.ValidationMessageFor(x => x.txtUsername, "", new { #class = "text-danger labeltiny" })
Pass the LoginModel as a paramater instead of the ViewModelVM in the controller like this (do the same with RegisterSubmit):
[HttpPost]
public ActionResult LoginSubmit(LoginModel lm)
{
ViewModelVM vm = new ViewModelVM();
if (ModelState.IsValid)
{
//perform other logic using form fields lm.txtUsername, etc...
return View("Index");
}
else
{
return View("Login", vm);
}
}

Update ViewModel after dynamically updating the view

I am trying to define ViewModels that faithfully represent the view (to make strict use of that concept).
Some of the elements of the ViewModel are updated dynamically. The problem I have, is that when I do the Post, the ViewModel returns without the elements that were updated dynamically.
The update is done through jQuery, when an event is performed. An action is invoked through Url.Action, and a Div is updated.
I made an example to clarify the scenario. An application that only stores a location (state and city). For this I have three ViewModels: one to represent the States in a SelectList, one to represent the Cities in a SelectList, and finally one to represent the Location (formed by the two ViewModel that I mentioned first).
Models:
public class State
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
public class City
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int StateId { get; set; }
public virtual State State { get; set; }
}
ViewModels:
public class CitySelectListViewModel
{
public CitySelectListViewModel() { }
public CitySelectListViewModel(IEnumerable<Models.City> cities)
{
this.Cities = cities;
}
[Display(Name = "Cities")]
[Required]
public int? SelectedCityId { get; set; }
public IEnumerable<City> Cities { get; }
}
public class StateSelectListViewModel
{
public StateSelectListViewModel() { }
public StateSelectListViewModel(IEnumerable<State> states)
{
this.States = states;
}
[Display(Name = "States")]
[Required]
public int? SelectedStateId { get; set; }
public IEnumerable<State> States { get; }
}
public class LocationCreateViewModel
{
public LocationCreateViewModel() { }
public LocationCreateViewModel(ICollection<State> states)
{
this.StateSelectListViewModels = new StateSelectListViewModel(states);
this.CitySelectListViewModel = new CitySelectListViewModel();
}
public StateSelectListViewModel StateSelectListViewModels { set; get; }
public CitySelectListViewModel CitySelectListViewModel { set; get; }
}
Location [Controller]:
public class LocationController : Controller
{
private DALDbContext db = new DALDbContext();
// GET: Location/Create
public ActionResult Create()
{
LocationCreateViewModel locationCreateViewModel = new LocationCreateViewModel(db.States.ToList());
return View(locationCreateViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(LocationCreateViewModel pLocationCreateViewModel)
{
if (ModelState.IsValid)
{
//db.States.Add(state);
//db.SaveChanges();
return RedirectToAction("Index", "Home");
}
LocationCreateViewModel locationCreateViewModel = new LocationCreateViewModel(db.States.ToList());
return View(locationCreateViewModel);
}
public ActionResult CitySelectList(int? stateId)
{
CitySelectListViewModel citySelectListViewModel = new CitySelectListViewModel(db.Cities.Where(c => c.StateId == stateId).ToList());
return View(citySelectListViewModel);
}
}
Create [View]:
#model ViewModelExample.ViewModels.LocationCreateViewModel
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>State</h4>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StateSelectListViewModels.SelectedStateId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateSelectListViewModels.SelectedStateId, new SelectList(Model.StateSelectListViewModels.States, "Id", "Name"), "Select a State", htmlAttributes: new { #class = "form-control", #id = "StateSelectList" })
#Html.ValidationMessageFor(model => model.StateSelectListViewModels.SelectedStateId, "", new { #class = "text-danger" })
</div>
</div>
<div id="CityContainer">
#Html.Action("CitySelectList")
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
// Fill City DropDownList
$('#StateSelectList').change(function () {
var selectedStateId = this.value;
$('#CityContainer').load('#Url.Action("CitySelectList")?stateId=' + selectedStateId);
});
});
</script>
}
CitySelectList [View]:
#model ViewModelExample.ViewModels.CitySelectListViewModel
....
<div class="form-group">
#Html.LabelFor(model => model.SelectedCityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedCityId, new SelectList(Model.Cities, "Id", "Name"), "Select a City", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedCityId, "", new { #class = "text-danger" })
</div>
</div>
I will show the execution of my example, and I will show the problem through the inspection of the ViewModel that I receive after the Post:
I select a State and a City, and I press Create.
I inspect the ViewModel received after the Post. We can see how CitySelectListViewModel is null, and what I want is to bring the last ViewModel that was updated through jQuery.
I admit that I have provided a long example, but it is the only way I found to explain what I need. Thanks in advance.
VS-Project of the example
I'ts because you are preventing the modelBinder to accurately bind to LocationCreateViewModel in your Create action when replacing the inner HTML of <div id="CityContainer"> (thats what you do with $('#CityContainer').load(...). You instruct the model binder to bind to
#model ViewModelExample.ViewModels.CitySelectListViewModel and as a result you get this HTML for the city select list:
One way of solving this is modifying CitySelectList.cshtml to:
#model ViewModelExample.ViewModels.LocationCreateViewModel
#{
Layout = null;
}
<div class="form-group">
#Html.LabelFor(model => model.CitySelectListViewModel.SelectedCityId,
htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model =>
model.CitySelectListViewModel.SelectedCityId, new
SelectList(Model.CitySelectListViewModel.Cities, "Id", "Name"), "Select a City", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CitySelectListViewModel.SelectedCityId, "", new { #class = "text-danger" })
</div>
</div>
and your CitySelectList action to:
public ActionResult CitySelectList(int? stateId)
{
LocationCreateViewModel locationCreateViewModel = new LocationCreateViewModel();
locationCreateViewModel.CitySelectListViewModel = new CitySelectListViewModel(db.Cities.Where(c => c.StateId == stateId).ToList());
return View(locationCreateViewModel);
}
But I would recommend custom model binding as well.

return list of ViewModel from model to controller [duplicate]

Whenever I submit the form the model passed into the controller is NULL. I've spent ages looking at this. I think I am missing something fundamental here.
#model VisitorPortal.Models.ReinviteVisitorModel
#using (Html.BeginForm("CreateMeeting", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h3>Reinvitation Details</h3>
<div>The information entered below will be sent to the visitors email address #Model.Info.Email</div>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.NewMeeting.Title, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewMeeting.Title, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.NewMeeting.StartTime, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewMeeting.StartTime, new { #class = "datetimepicker form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.NewMeeting.EndTime, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewMeeting.EndTime, new { #class = "datetimepicker form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#Html.HiddenFor(m => m.NewMeeting.SubjectId, new { #Value = Model.Info.SubjectId })
<input type="submit" class="btn btn-default" value="Send Invite" />
</div>
</div>
}
The Model is:
public class Meeting
{
[Key]
public int Id { get; set; }
public string SubjectId { get; set; }
[Required]
[Display(Name = "Reason for invitation")]
public string Title { get; set; }
[Required]
[Display(Name = "Start Time")]
[DataType(DataType.Time)]
public DateTime StartTime { get; set; }
[Required]
[Display(Name = "End Time")]
[DataType(DataType.Time)]
public DateTime EndTime { get; set; }
public string HostEmail { get; set; }
public string HostMobile { get; set; }
}
public class MeetingsDBContext: DbContext
{
public DbSet<Meeting> Meetings { get; set; }
}
public class ReinviteVisitorModel
{
public Visitor Info;
public Meeting NewMeeting;
public List<Meeting> Meetings;
}
The Controller action is:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMeeting(Meeting meeting)
{
return RedirectToAction("ReinviteVisitor2", "Home", new { visitorId = meeting.SubjectId });
}
I have fields in the model such as Id which I am expecting the database to populate which I was going to write in the the action CreateMeeting(). Do all fields in the Model have to be used in the form?
The model in your view is typeof ReinviteVisitorModel which means the signature of the POST method must match since your posting ReinviteVisitorModel
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMeeting(ReinviteVisitorModel model)
alternatively you can use the Prefix property of BindAttribute to strip the NewMeeting prefix from the names of the form controls your are posting.
public ActionResult CreateMeeting([Bind(Prefix="NewMeeting")]Meeting model)
Side note: Remove new { #Value = Model.Info.SubjectId } from the hidden input and instead set the value of NewMeeting.SubjectId in the GET method before you pass the model to the view.
You need to pass ReinviteVisitorModel model in your Action
Update you action with this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateMeeting(ReinviteVisitorModel model)
{
return RedirectToAction("ReinviteVisitor2", "Home", new { visitorId = model.NewMeeting.SubjectId });
}

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Practice' - MVC5

I am very new to MVC and have just added a cascading drop down to my create page so when a Practice is selected the Optician drop down is populated with the names of opticians that work at that practice.
Model:
public class Booking
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid BookingId { get; set; }
[ForeignKey("Patient")]
public Guid PatientId { get; set; }
public virtual Patient Patient { get; set; }
public IEnumerable<SelectListItem> PatientList { get; set; }
[ForeignKey("Practice")]
public Guid PracticeId { get; set; }
public virtual Practice Practice { get; set; }
public IEnumerable<SelectListItem> PracticeList { get; set; }
[ForeignKey("Optician")]
public Guid OpticianId { get; set; }
public virtual Optician Optician { get; set; }
public IEnumerable<SelectListItem> OpticiansList { get; set; }
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Date { get; set; }
[ForeignKey("Time")]
public Guid? TimeId { get; set; }
public virtual Time Time { get; set; }
public IEnumerable<SelectListItem> TimeList { get; set; }
public bool isAvail { get; set; }
}
My Controller:
// GET: Bookings1/Create
public ActionResult Create()
{
var practices = new SelectList(db.Practices, "PracticeId", "PracticeName");
ViewData["Practice"] = practices;
Booking booking = new Booking();
ConfigureCreateModel(booking);
return View(booking);
}
public void ConfigureCreateModel(Booking booking)
{
booking.PatientList = db.Patients.Select(p => new SelectListItem()
{
Value = p.PatientId.ToString(),
Text = p.User.FirstName
});
booking.TimeList = db.Times.Select(t => new SelectListItem()
{
Value = t.TimeId.ToString(),
Text = t.AppointmentTime
});
}
// POST: Bookings1/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Booking booking)
{
// to ensure date is in the future
if (ModelState.IsValidField("Date") && DateTime.Now > booking.Date)
{
ModelState.AddModelError("Date", "Please enter a date in the future");
}
// Sets isAvail to false
booking.isAvail = false;
//Checks if model state is not valid
if (!ModelState.IsValid)
{
ConfigureCreateModel(booking);
return View(booking); // returns user to booking page
}
else // if model state is Valid
{
// Generates a new booking Id
booking.BookingId = Guid.NewGuid();
// Adds booking to database
db.Bookings.Add(booking);
// Saves changes to Database
db.SaveChanges();
// Redirects User to Booking Index
return RedirectToAction("Index");
}
}
My View:
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$("#Optician").prop("disabled", true);
$("#Practice").change(function () {
$.ajax({
url : "#Url.Action("Opticians","Bookings")",
type : "POST",
data : {Id : $(this).val() }
}).done(function (opticianList) {
$("#Optician").empty();
for (var i = 0; i < opticianList.length; i++) {
$("#Optician").append("<option>" + opticianList[i] + "</option>");
}
$("#Optician").prop("disabled", false);
});
});
});
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Booking</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.PatientId, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.PatientId, Model.PatientList, "-Please select-", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PatientId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PracticeId, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Practice", ViewData["Practice"] as SelectList,"-Please Select-", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PracticeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Select Optician :", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<select id="Optician"></select>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeId, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TimeId, Model.TimeList, "-Please select-", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TimeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
The cascading drop down works as it should how ever when I click the button to create the appointment the following exception is thrown:
Exception:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: There is no ViewData item of type 'IEnumerable' that has the key 'Practice'.
Any help would be greatly appreciated.
Thanks
You model already contains a property for the collection of practices
public IEnumerable<SelectListItem> PracticeList { get; set; }
although it should not contain
public virtual Practice Practice { get; set; }
In the GET method, you create a new SelectList for practices, but instead of assigning it to the model property, you add it to ViewData using
ViewData["Practice"] = practices;
and then in the view use
#Html.DropDownList("Practice", ViewData["Practice"] as SelectList, ..)
which is not even binding to a property in your model and would never post back to anything. Then when you return the view in the POST method (because your mode will always be invalid), you do not assign a value to ViewData["Practice"] so its null, hence the error.
Instead, in your ConfigureCreateModel() method, populate the PracticeList property (as your doing for PatientList) and remove the use of ViewData, and in the view use
#Html.DropDownListFor(model => model.PracticeId, Model.PracticeList, ...)
so your strongly binding to your model and when your submit the form, the value of PracticeId will be the value of the selected practice.
Side note: You will need to change your script to $("#PracticeId").change(function () { ...

Why is my View not displaying value of ViewBag?

I have a little blog application with posts and tags. This is my model for Post:
namespace HelloWorld.Models
{
public class Post
{
[Required]
[DataType(DataType.Text)]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime PostDate { get; set; }
public List<Tag> Tags { get; set; }
[Required]
public int PostId { get; set; }
}
public class CreatePostView
{
[Required]
[DataType(DataType.Text)]
public string Title { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Tags")]
[Required(ErrorMessage = "Please select a tag")]
public string SelectedTag { get; set; }
public SelectList TagList { get; set; }
[Required]
public int PostId { get; set; }
}
}
And model of Tag consist of string TagName, int TagId, List Posts.
When I create a new Post I use CreatePostView and my view is:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="create-post-form">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<strong>Title</strong>
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<strong>Description</strong>
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
#Html.DropDownListFor(m => m.SelectedTag, Model.TagList, "Add tag")
#Html.ValidationMessageFor(m => m.SelectedTag)
<div class="post-create-button">
<input type="submit" value="Create">
</div>
<div class="back-to-list-button">
#Html.ActionLink("Back", "Index")
</div>
</div>
}
And now I want to display my tag that I selected. I put value of selected tag in ViewBag, but it does not display. Maybe it's silly, but I do not know how to fix it. My Create action of PostsController:
// POST: Posts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreatePostView post)
{
Post currPost = new Post {
Title = post.Title,
Description = post.Description,
PostDate = DateTime.Now,
Tags = null };
ViewBag.Tag = post.SelectedTag.ToString();
ViewBag.Trash = "texttexttexttexttext"; // It's strange, but it not displayed.
if (ModelState.IsValid)
{
//var tags = db.Tags.Where(s => s.TagName.Equals(post.SelectedTag)).ToList();
//currPost.Tags = tags;
db.Posts.Add(currPost);
db.SaveChanges();
return RedirectToAction("Index", "Posts");
}
return View(currPost);
}
My view with all Posts (use model Post)
#foreach (var item in Model)
{
<article class="post">
<h3>#Html.DisplayFor(modelItem => item.Title)</h3>
<p>#Html.DisplayFor(modelItem => item.Description)</p>
<!--None of them is not shown-->
<p><strong>Tag: #ViewBag.Tag</strong></p>
<p><strong>Trash: #ViewBag.Trash</strong></p>
</article>
}
ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead:
TempData["Tag"] = post.SelectedTag.ToString();
and in the view:
<p><strong>Tag: #TempData["Tag"]</strong></p>

Categories

Resources