DateTime default value ASP.net core - c#

For a student project, I want to add default value - in the date field(ReleaseDate) but still have a calendar and the option of choosing a date.
My code in Models/Post.cs:
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode =true, DataFormatString = "{0: yyyy-MM-dd}")]
public System.DateTime ReleaseDate { get; set; }
And in View/Posts/Create.cshtml:
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
I try timur but
Controllers/PostController.cs
Is see only one define of index:
public async Task<IActionResult> Index()
{
return View(await _context.Movie.ToListAsync());
}
And your code:
public IActionResult Index()
{
var model = new Post()
{
ReleaseDate = DateTime.Today
};
return View("View", model);
}
I try to put like that
But there is an error (on https://localhost:numbers/Posts
Views/Posts/Create.cshtml
#model Portal.Models.Post
#{
ViewData["Title"] = "Create -";
}
<h1>Create</h1>
<h4>Post</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
And Views/Posts/Index.cshtml
#model IEnumerable<Portal.Models.Post>
#{
ViewData["Title"] = "Job Rice -";
}
<!-- Image -->
<section>
<div class="container">
<div class="full-width-image">
<img src="img/background.jpg" alt="">
</div>
</div>
</section>
<div class="text-center">
<h1><a asp-action="Create">Create new offer</a></h1>
</div>
#foreach (var item in Model)
{
<section>
<div class="container">
<!-- Heading -->
<div class="my-5"> </div>
<!-- Grid row -->
<div class="row">
<!-- Grid column -->
<div class="col-sm-12 sm-12">
<!-- Card -->
<div class="card">
<div class="card-header text-center colores">
<h4> <i class="fas fa-poll-h"></i> <a asp-action="Details" asp-route-id="#item.Id"> #Html.DisplayFor(modelItem => item.Title) </a></h4>
</div>
<!-- Card content -->
<form class="card-body">
<div class="row">
<div class="col-sm-12">
<div class="text-center"> #Html.DisplayFor(modelItem => item.Description)</div>
<div class="float-right"> #Html.DisplayFor(modelItem => item.ReleaseDate)</div>
</div>
<div>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a>
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
}

As Tieson T. points in his comment, you have to add the "value" attribute to the "input" tag in your razor page:
<input asp-for="ReleaseDate" class="form-control" value="#DateTime.Today.ToString("yyyy-MM-dd")" />
Of course, you can replace "DateTime.Today" with something else.
It doesn't matter that your browser shows the date in different format, you have to use this one inside the value attribute. I just tested it in an ASP.NET Core 3.1 Razor app and it works.

This should instantiate a default value:
public System.DateTime ReleaseDate { get; set; } = System.DateTime.Today;
alternatively if you need time as well
public System.DateTime ReleaseDate { get; set; } = System.DateTime.Now;

Since Razor views still allow you write html, you could try to define yours as
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" value="#Model.ReleaseDate.ToString("yyyy-MM-dd")" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
it should render the current model value as starting point for your input, of course you need to define one before passing it down onto a view:
public IActionResult Index()
{
var model = new Post()
{
ReleaseDate = DateTime.Today
};
return View("View", model);
}

You can use the following Razor syntax for this purpose.
<input type="date" asp-for="ReleaseDate" class="form-control" value=#DateTime.Today.ToString("yyyy-MM-dd") />
You just have to put type=date.

Related

Razor page I lost the User data Passed from the user page when I call it from the post method

because I need to create my user info in many different tables with many different Models and views I used this code in the address page but as shown in my remarks I lost the user info in the post function My question is why and what to do????? by the way when I copied the User1 difenation from my OnGet function to the OnPost function this code work perfectly as explained in my comment but I still want to understand why a public property lose the information please read my comments
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using RazorPagesUI.Models;
namespace RazorPagesUI.Pages.Forms
{
partial class AddAddressModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public AddAddressModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty(SupportsGet = true)]
public string Mail { get; set; }
public IEnumerable<SelectListItem>? Country { get; set; }
[BindProperty]
public AddressModel? Address { get; set; }
public string SelectedString { get; set; }
public UserModel User1 { get; set; }=new UserModel();
public void OnGet()
{
List<string> TagIds = Mail.Split(',').ToList();
Int32.TryParse(TagIds[0], out int j);
User1.Id = j;
User1.Email = TagIds[1];
User1.FirstName = TagIds[2];
User1.LastName = TagIds[3];
User1.Password = TagIds[4]
Country = new SelectListItem[]
{
new SelectListItem ("Canada", "Canada"),
new SelectListItem ("Egypt", "Egypt"),
new SelectListItem ( "Usa", "Usa")
};
}
public IActionResult OnPost()
{
//when I get to here User1 is null
Address.Country = Request.Form["country"];
if (ModelState.IsValid == false)
{
return Page();
}
//I need to insert my user info to my user table but User1 is null
//here I insert Address info
return RedirectToPage("/index", new{ Name = User1.Firstname);//User1
becomes Null
}
}
}
cshtml file As asked to include in my post
#page
#using RazorPagesUI.Models
#model RazorPagesUI.Pages.Forms.AddAddressModel
#{
ViewData["Title"] = "Add Address";
}
<b>Adderres for: #Model.User1.FirstName #Model.User1.LastName</b>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<div class="text-center">
<h1>Add Address</h1>
</div>
<form method="post">
<div class="container-fluid">
<div class="p-1">
<div class="text-center">
<select name = "country" asp-items="#Model.Country">
</select>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.State" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.City"
/>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetNumber"
placeholder="Street #" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetName"
placeholder="Street Name" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.AppNumber"
placeholder="App#" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.ZipCode" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.Phone" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.CellPhone" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<button type="submit">Submit</button>
</div>
</div>
</div>
</form>
Firstly,you need to pass User1.FirstName when form post,so that you can get User1.FirstNamein OnPost handler.
form(add hidden input with User1.FirstName):
<form method="post">
<div class="container-fluid">
<div class="p-1">
<div class="text-center">
<select name = "country" asp-items="#Model.Country">
</select>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.State" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.City"
/>
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetNumber"
placeholder="Street #" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.StreetName"
placeholder="Street Name" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.AppNumber"
placeholder="App#" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="text" asp-for="Address.ZipCode" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.Phone" />
</div>
</div>
<div class="p-1">
<div class="text-center">
<input type="tel" asp-for="Address.CellPhone" />
</div>
</div>
<div class="text-center">
<div class="p-1">
<input type="hidden" asp-for="User1.FirstName" />
<button type="submit">Submit</button>
</div>
</div>
</div>
</form>
cshtml.cs(If you want to bind the data to User1,you need to use [BindProperty],so that you can use User1.Firstname in OnPost handler):
[BindProperty]
public UserModel User1 { get; set; } = new UserModel();
You have to show your cshtml file i.e. the front end of the Razor page for a more clear description of your problem. But in general, I'm seeing that you are trying to bind a property called Country of a complex object called Address of type AddressModel In this case the name of the input/select in your cshtml file should reflect the complex path to the target Country property of the Address object. It should be something like this <select name="Address.Country" asp-items="Model.Country"></select> Notice the name of the select element Address.Country i.e. it reflects the full path to the target property. More information on complex model binding in razor pages here https://www.learnrazorpages.com/razor-pages/model-binding If you manage to bind the property of the complex object correctly this line of code Address.Country = Request.Form["country"]; becomes redundant. The value of Address.Country should be populated automatically.

Insert a combobox inside view in .NET Core

I have a view page to insert some data.
here is the model:
#model BookListMVC.Models.Book
I need to insert a combobox linked to another table "Categories".
The compiler does not allow me to insert multiple models because that is probably not the right way.
How I can insert a combobox linked to "Categories" that point to book "IdCategory" ?
Here the actual code full inside:
#model BookListMVC.Models.Book
<br />
<h2 class="text-info">#(Model.Id!=0 ? "Edit" : "Create") Book</h2>
<br />
<div class="border container" style="padding:30px;">
<form method="post">
#if (Model.Id != 0)
{
<input type="hidden" asp-for="Id" />}
<div class="text-danger" asp-validation-summary="ModelOnly"></div>
<div class="form-group row">
<div class="col-3">
<label asp-for="Name"></label>
</div>
<div class="col-6">
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<label asp-for="Author"></label>
</div>
<div class="col-6">
<input asp-for="Author" class="form-control" />
<span asp-validation-for="Author" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<label asp-for="ISBN"></label>
</div>
<div class="col-6">
<input asp-for="ISBN" class="form-control" />
<span asp-validation-for="ISBN" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3">
<label asp-for="ISBN"></label>
</div>
<div class="col-6">
<input asp-for="ISBN" class="form-control" />
<span asp-validation-for="ISBN" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-3 offset-3">
<button type="submit" class="btn btn-primary form-control">
#(Model.Id != 0 ? "Update" : "Create")
</button>
</div>
<div class="col-3">
<a asp-action="Index" class="btn btn-success form-control">Back to List</a>
</div>
</div>
</form>
</div>
You can insert the combobox model through ViewBag or ViewData. For example.
public IActionResult Index()
{
//The data can be obtained from database.
ViewBag.Categories = new List<SelectListItem>
{
new SelectListItem{ Text="history", Value="1"},
new SelectListItem{ Text="literature", Value="2"},
};
var model = new Book { Id = 2, Author="author", ISBN="isbn", Name="bookname" };
return View(model);
}
This is the simple combobox in the view.
<div class="form-group row">
<div class="col-3">
<label asp-for="categories"></label>
</div>
<div class="col-6">
<select asp-for="categories" name="CategoryId" asp-items="ViewBag.Categories">
<option>-- select the category --</option>
</select>
<span asp-validation-for="categories" class="text-danger"></span>
</div>
</div>
Model (Categories)
public class Categories
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
Result
You can add a property CategoryId in model Book, even add a property Categories.
public class Book
{
public int CategoryId { get; set; }
public Categories categories { get; set; }
}
If you want to pass the object Categories to the bakend, you can add a hidden input box and relative javascript.
Add hidden box.
<div class="form-group row">
<div class="col-3">
<label asp-for="categories"></label>
</div>
<div class="col-6">
<select onchange="changeName()" asp-for="categories" name="categories.CategoryId" asp-items="ViewBag.Categories">
<option>-- select the category --</option>
</select>
<input type="hidden" name="categories.CategoryName" value="" id="categoryName"/>
<span asp-validation-for="categories" class="text-danger"></span>
</div>
</div>
Add javascript.
#section Scripts{
<script>
function changeName() {
var index = document.getElementById("categories").selectedIndex;
var text = document.getElementById("categories").options[index].text;
document.getElementById("categoryName").value=text
}
</script>
}
Then you can get all data include Categories and can handling Categories table.

how to properly fix MVVM scaffolding issue with duplicate name tag? (ASP Core 2.2)

Here's my problem, I have a Book that contains List<Page> that contains List<Line> and I'm trying to create a view that will edit my book. This view contains all the lines from the book. I've made an MVVM for List<Page> that calls smaller MVVM for List<Line>. The problem is that MVVM is not counting all Line as one single form, so this happens:
<form>
<h1>Page one</h1>
<input type="hidden" name="[0].lineContent" value=""/>
<input type="hidden" name="[1].lineContent" value=""/>
<h1>Page one</h1>
<input type="hidden" name="[0].lineContent" value=""/>
<input type="hidden" name="[1].lineContent" value=""/>
<input type="hidden" name="[2].lineContent" value=""/>
</form>
Each time my for loop for page iterates, my for loops in lines get reset to 0, this creates duplicate name entries.
There are multiple ways to correct this, the easiest:
Build input by hand with unique name id instead of using HTML helpers
My question is the following: how can I achieve a clean razor that can be reused, and that will not duplicate name entries in my form?
UPDATE:
Context:
Just like the book exemple up, my models have the same structure.
in my case I have a Submission that contains a list of Section that contains a list of SubSection that contains a list of SubmissionLine.
Here's my main view:
#model
QuotingPlus.Models.Submission
#{
ViewData["Title"] = "Edit";
}
<form id="submission-form" asp-action="Edit">
<div>
<p class="d-inline-block">
<a class="btn btn-primary" data-toggle="collapse"
href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Edit submission details</a>
</p>
<nav aria-label="breadcrumb" class="d-inline-block">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="/Clients/Details/#(Model.IdProjectNavigation.IdClientNavigation.IdClient)">#Model.IdProjectNavigation.IdClientNavigation.FirstName
#Model.IdProjectNavigation.IdClientNavigation.LastName</a>
</li>
<li class="breadcrumb-item">
#Model.IdProjectNavigation.Name
</li>
<li class="breadcrumb-item active" aria-current="page">#Model.Number</li>
</ol>
</nav>
</div>
<div class="row">
<div class="col mb-3">
<div class="collapse multi-collapse" id="multiCollapseExample1">
<div class="card card-body">
<h1>Submission details</h1>
<hr/>
<div class="row">
<div class="col-md-4">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="IdSubmission"/>
<div class="form-group">
<label asp-for="IdTypeSubmission" class="control-label"></label>
<select asp-for="IdTypeSubmission" class="form-control" asp-items="ViewBag.IdTypeSubmission"></select>
<span asp-validation-for="IdTypeSubmission" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="IdProject" class="control-label"></label>
<select asp-for="IdProject" class="form-control" asp-items="ViewBag.IdProject"></select>
<span asp-validation-for="IdProject" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Number" class="control-label"></label>
<input asp-for="Number" class="form-control"/>
<span asp-validation-for="Number" class="text-danger"></span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="save-warning" style="display: none;" class="alert alert-info alert-dismissible fade show" role="alert">
<strong>WARNING!</strong> Make sure you save before leaving.
<button type="button" class="close" data-dismiss="alert" aria-label="Close" onclick="SetWarningDisplayPreferenceCookie();">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="carouselIndicators" style="height: 100% !important;" class="carousel slide pb-5 mb-5" data-interval="false">
<div class="carousel-inner">
#{
Html.RenderPartial("SubmissionSectionEditor", Model.SubmissionSection.ToList());
}
</div>
<nav class="navbar navbar-light bg-secondary mb-0 pt-2 fixed-bottom">
<div>
<button type="submit" value="Save" class="btn btn-default text-white">
<i class="material-icons" style="font-size: 2em;">
save
</i>
</button>
</div>
<a class="col text-center mh-100 pt-2 pb-2" href="#carouselIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="false"></span>
</a>
<a class="col text-center mh-100 pt-2" href="#carouselIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="false"></span>
</a>
<div>
<a asp-action="Index" class="btn text-white">
<i class="material-icons" style="font-size: 2em;">
cancel
</i>
</a>
</div>
</nav>
</div>
</form>
Here's SubmissionSectionEditor.cshtml
#model List<SubmissionSection>
#{
var isFirstCarouselItem = true;
}
#for (var indexSection = 0; indexSection < Model.Count(); indexSection++)
{
<div class="carousel-item #((isFirstCarouselItem) ? "active" : "")">
#{
isFirstCarouselItem = false;
}
<h1>#Model[indexSection].IdSectionNavigation.Name</h1>
<div id="#(Model[indexSection].IdSection + "accordion")">
#{
var submissionSubSections = M odel[indexSection].SubmissionSubSection;
}
#if (submissionSubSections != null)
{
Html.RenderPartial("SubmissionSubSectionEditor", submissionSubSections.ToList());
}
</div>
</div>
}
Here's SubmissionSubSectionEditor.cshtml
#model List<SubmissionSubSection>
#for (var indexSubSection = 0; indexSubSection < Model.Count; indexSubSection++)
{
<div class="card">
<div class="card-header" id="#(Model[indexSubSection].IdSubSection + "SubSectionHeader")">
<h2 class="mb-0">
<button type="button" class="btn btn-link collapsed" data-toggle="collapse" data-target="#("#" + Model[indexSubSection].IdSubSection + "SubSectionCollapse")" aria-
expanded="true" aria-controls="#(Model[indexSubSection].IdSubSection + "SubSectionCollapse")">
#Model[indexSubSection].IdSubSectionNavigation.Name
</button>
</h2>
</div>
<div id="#(Model[indexSubSection].IdSubSection + "SubSectionCollapse")" class="collapse" aria-labelledby="#(Model[indexSubSection].IdSubSection +
"SubSectionHeader")" data-parent="#("#" + Model[indexSubSection].IdSubmissionSectionNavigation.IdSection + "accordion")">
<div class="card-body">
<table class="table w-100">
<thead class="thead-dark">
<tr>
<th>Quantity</th>
<th>Article</th>
<th>Total Material</th>
<th>Unit Price Material</th>
<th>Total Sub Contractor</th>
<th>Unit Price Sub Contractor</th>
<th>Total Workforce</th>
<th>Unit Price Workforce</th>
<th>Display</th>
</tr>
</thead>
<tbody>
#{
Html.RenderPartial("SubmissionLineEditor", Model[indexSubSection].SubmissionLine.ToList());
}
</tbody>
</table>
</div>
</div>
</div>
}
Here's SubmissionLineEditor.cshtml
#model List<SubmissionLine>
#for (var indexLine = 0; indexLine < Model.Count; indexLine++)
{
<tr>
#Html.HiddenFor(x => Model[indexLine].IdSubmissionLine)
#Html.HiddenFor(x => Model[indexLine].IdArticle)
#Html.HiddenFor(x => Model[indexLine].IdSubmissionSubSection)
<td>#Html.TextBoxFor(x => Model[indexLine].Quantity, new {#type = "number", #step = "0.5", #min="0"})</td>
<td>#Model[indexLine].IdArticleNavigation.Designation</td>
<td>#Model[indexLine].TotalMaterial</td>
<td>#Model[indexLine].IdArticleNavigation.UnitPriceMaterial</td>
<td>#Model[indexLine].TotalSubContractor</td>
<td>#Model[indexLine].IdArticleNavigation.UnitPriceSubContractor</td>
<td>#Model[indexLine].TotalWorkforce</td>
<td>#Model[indexLine].IdArticleNavigation.UnitPriceWorkforce</td>
<td>#Html.CheckBoxFor(x => Model[indexLine].IsDisplayed, new {#class = "checkbox"}).
</td>
</tr>
}
I only want to know how I can keep this structure with MVVM and avoid the input name duplicate issue?
RE-UPDATE:
I'm not quite sure why this would be useful since I get name duplicate input, but here's my save action:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin, SuperAdmin, Employe")]
public ActionResult Edit(int id, Submission submission, [FromForm] List<SubmissionLine> lines)
{
var test = Request.Form;
if (id != submission.IdSubmission)
{
return NotFound();
}
if (ModelState.IsValid)
{
SubmissionUpdateHelper.SaveSubmissionModifications(_context, submission, lines);
return RedirectToAction(nameof(Index));
}
ViewData["IdProject"] = new SelectList(_context.Project, "IdProject", "Name", submission.IdProject);
ViewData["IdTypeSubmission"] = new SelectList(_context.TypeSubmission, "IdTypeSubmission",
"TypeSubmission1", submission.IdTypeSubmission);
return View(submission);
}
For showing sub-list properties in View, Try code below:
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="BookName" class="control-label"></label>
<input asp-for="BookName" class="form-control" />
<span asp-validation-for="BookName" class="text-danger"></span>
</div>
<div class="form-group">
#for (int i = 0; i < Model.Pages.Count; i++)
{
<div class="form-group">
<label asp-for="Pages[i].PageName" class="control-label"></label>
<input asp-for="Pages[i].PageName" class="form-control" />
<span asp-validation-for="Pages[i].PageName" class="text-danger"></span>
</div>
<div class="form-group">
#for (int j = 0; j < Model.Pages[i].Lines.Count; j++)
{
<div class="form-group">
<label asp-for="Pages[i].Lines[j].LineContent" class="control-label"></label>
<input asp-for="Pages[i].Lines[j].LineContent" class="form-control" />
<span asp-validation-for="Pages[i].Lines[j].LineContent" class="text-danger"></span>
</div>
}
</div>
}
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Finally, I've just added the input by hand so I could keep my MVVM pattern. I've also used an increment variable in TempData so I could keep track of the input
in Edit.cshtml
#{
TempData["submissionLineCount"] = 0;
}
here's the new version of SubmissionLineEditor.cshtml
#model List<SubmissionLine>
#for (var indexLine = 0; indexLine < Model.Count; indexLine++)
{
<tr>
<input name="[#(TempData["submissionLineCount"])].IdSubmissionLine" value="#(Model[indexLine].IdSubmissionLine)" type="hidden"/>
<input name="[#(TempData["submissionLineCount"])].IdArticle" value="#(Model[indexLine].IdArticle)" type="hidden"/>
<input name="[#(TempData["submissionLineCount"])].IdSubmissionSubSection" value="#(Model[indexLine].IdSubmissionSubSection)" type="hidden"/>
<td>#TempData["submissionLineCount"]</td>
<td>
<input name="[#(TempData["submissionLineCount"])].Quantity" value="#(Model[indexLine].Quantity)" type="number" step="0.5" min="0"/>
</td>
<td>#Model[indexLine].IdArticleNavigation.Designation</td>
<td>#Model[indexLine].TotalMaterial</td>
<td>#Model[indexLine].IdArticleNavigation.UnitPriceMaterial</td>
<td>#Model[indexLine].TotalSubContractor</td>
<td>#Model[indexLine].IdArticleNavigation.UnitPriceSubContractor</td>
<td>#Model[indexLine].TotalWorkforce</td>
<td>#Model[indexLine].IdArticleNavigation.UnitPriceWorkforce</td>
<td>
<input type="checkbox" name="[#(TempData["submissionLineCount"])].IsDisplayed" class="checkbox" value="#(Model[indexLine].IsDisplayed)"/>
</td>
</tr>
{
TempData["submissionLineCount"] = (Convert.ToInt32(TempData["submissionLineCount"]) + 1);
}
}
This is clearly not the best way, I hope there will be more documentation on how to apply MVVM in AspNet.Core in the future...
If this answer gets deprecated, make sure to post your own!

ASP.NET Core 2.1 Unobtrusive Ajax Validation Not Working With Partial View Form Swap

I've spent several hours combing Stackoverflow and other sites trying everyone's solutions with no luck so far. I'm sure I've missed something, but I can't see it. Hopefully you can point me to a fix.
I have an initial form inside a partial view that is rendered into a parent view whose validation works fine. Once the form is submitted via Ajax replace, I return either a login or registration partial view with a new form in the response. This second form will not display the model validation errors when an incomplete form is submitted and the same partial view is returned.
Thanks in advance for any tips you can offer to bring an end to this insanity!
Parent View Section
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="panel panel-primary" id="formData">
#await Html.PartialAsync("_UserNamePartial", new UserNameViewModel())
</div>
</div>
</div>
Working Rendered Partial View
<div class="panel-heading">
<h3 class="panel-title">Let's Start With Your E-mail Address</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<form asp-controller="Account" asp-action="IsAccountValid" data-ajax="true" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#formData">
#Html.AntiForgeryToken()
<div class="form-group">
<label for="UserName">Your Email Address</label>
<div class="input-group">
<input type="text" id="UserName" name="UserName" class="form-control" placeholder="Your email address" />
<div class="input-group-btn">
<button type="submit" id="btnGetStarted" class="btn btn-primary">Get Started</button>
</div>
</div>
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</form>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
</div>
</div>
</div>
Initial Validation Controller Action
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult IsAccountValid(UserNameViewModel model)
{
if (!ModelState.IsValid)
return PartialView("../Home/_UserNamePartial", model);
AccountRepository accountRepository = new AccountRepository(ConnectionConfig.InshoraDev);
AuthName match = accountRepository.GetAuthName(model.UserName);
if (match != null)
{
ModelState.Clear();
LoginViewModel loginModel = new LoginViewModel()
{
UserName = model.UserName
};
return PartialView("_UserLoginPartial", loginModel);
}
ModelState.Clear();
SignUpViewModel signupModel = new SignUpViewModel()
{
UserName = model.UserName,
};
return PartialView("_UserSignUp", signupModel);
}
Login Partial View (Validation Error Display Not Working)
#model Inshora.Models.Account.LoginViewModel
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="panel-heading">
<h3 class="panel-title">Log Into Your Account</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<form id="login-form" asp-controller="Account" asp-action="Login" method="post" role="form" style="display: block;"
data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="formData" data-ajax-complete="AcctLib.Login.Events.onComplete">
#Html.AntiForgeryToken()
<div class="form-group">
<input type="text" name="UserName" id="UserName" tabindex="1" class="form-control" placeholder="Email Address" value="#Model.UserName">
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="password" name="Password" id="Password" tabindex="2" class="form-control" placeholder="Password">
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group text-center">
<input type="checkbox" tabindex="3" class="" name="RememberMe" id="RememberMe">
<label for="RememberMe"> Remember Me</label>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-primary" value="Log In">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
<a id="PasswordReset" asp-controller="Account" asp-action="PasswordReset" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#formData" tabindex="5" class="inshora-forgot-password">Forgot Password?</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
AcctLib.Login.Init();
})
</script>
LoginViewModel
public class LoginViewModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public bool RememberMe { get; set; }
}
Client Side Initialization Code
AcctLib.Login.RebindForm = function() {
$('form').each(function (i, f) {
$form = $(f);
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
});
}
AcctLib.Login.Init = function () {
AcctLib.Login.RebindForm();
$('#UserName').focus();
}
Update
I have updated the parent page (index.cshtml) to the following and it still doesn't display the messages.
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="panel panel-primary" id="formData">
#await Html.PartialAsync("_UserNamePartial", new UserNameViewModel())
</div>
</div>
</div>
#section Scripts
{
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
The problem was that I had not used the asp-for tag helpers. Those helpers are responsible for generating the data-* attributes needed by the unobtrusive validation parser. Once I started using them it started working. Thank you to everyone who tried to help.
Corrected View
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<form id="login-form" asp-controller="Account" asp-action="Login" method="post" role="form"
data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" data-ajax-update="#formData">
#Html.AntiForgeryToken()
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName"></label>
<input asp-for="UserName" class="form-control" placeholder="Email Address"/>
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" placeholder="Password"/>
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group text-center">
<input asp-for="RememberMe" />
<label asp-for="RememberMe"> Remember Me</label>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-primary" value="Log In">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
<a id="PasswordReset" asp-controller="Account" asp-action="PasswordReset" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#formData" tabindex="5" class="inshora-forgot-password">Forgot Password?</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
if (!ModelState.IsValid)
return PartialView("..\\Home\\_UserNamePartial", model);
pretty sure this violates pathing
if(!ModelState.IsValid)
return PartialView("../Home/_UserNamePartial", model);
Cut renderPartial link and paste to before #script section, like below:
#{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
#section Scripts
{
}

Editing an item inline in the Index-view throws off model binding. How to make it work?

I am trying to make a system where the user can click on an item in a list, and then edit that item while still remaining in the Index-view.
My attempt is just a mix between Index.cshtml and Edit.cshtml:
#model IEnumerable<MyStore.Models.ProductIdentifier>
#{int primary_id = (this.ViewContext.RouteData.Values["primary_id"] != null
? int.Parse(this.ViewContext.RouteData.Values["primary_id"].ToString())
: 0);
}
#foreach (var item in Model)
{
if (item.Id == primary_id)
{
// This list-item is editable (copied from Edit.cshtml):
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="#item.Id" />
<div class="form-group col-lg-4">
<input asp-for="#item.Label" class="form-control" />
<span asp-validation-for="#item.Label" class="text-danger"></span>
</div>
<div class="form-group col-lg-6">
<input asp-for="#item.Description" class="form-control" />
<span asp-validation-for="#item.Description" class="text-danger"></span>
</div>
<div class="form-group col-lg-1">
<input asp-for="#item.SortOrder" class="form-control" />
<span asp-validation-for="#item.SortOrder" class="text-danger"></span>
</div>
<div class="form-group col-lg-1">
<button type="submit" value="Save" class="btn btn-primary">
<span class="glyphicon glyphicon-floppy-disk"></span> Save
</button>
</div>
</form>
}
else
{
// This list-item is just a plain list-item:
<div class="row table">
<div class="col-lg-4">
<a asp-action="Index" asp-route-primary_id="#item.Id">
#Html.DisplayFor(modelItem => item.Label)
</a>
</div>
<div class="col-lg-6">
#Html.DisplayFor(modelItem => item.Description)
</div>
<div class="col-lg-1">
#Html.DisplayFor(modelItem => item.SortOrder)
</div>
<div class="col-lg-1">
<a asp-action="Delete" asp-route-id="#item.Id" class="btn btn-xs btn-danger">
<span class="glyphicon glyphicon-trash"></span>
</a>
</div>
</div>
}
}
The form data is supposed to be posted to the Edit-method in the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Label,Description,SortOrder")] ProductIdentifier productIdentifier)
{
if (id != productIdentifier.Id) { return NotFound(); }
if (ModelState.IsValid)
{
try
{
_context.Update(productIdentifier);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductIdentifierExists(productIdentifier.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(productIdentifier);
}
... but because I had to add #item. in front of the elements in the form (because the model is an IEnumerable, and I only want to post a single object), the model binding no longer works, and a null object is being posted.
How can I get it to work?
I made it work!
First, I created a ViewModel which contains both an ICollection of identifiers and a single instance of an identifier:
public class ViewModelEditIdentifierInIndexView
{
public ViewModelProductIdentifier SingleItem { get; set; }
public ICollection<ViewModelProductIdentifier> ListOfItems { get; set; }
}
I had to make some changes in the Index method in the controller, to cater for the viewmodel:
public async Task<IActionResult> Index(int? primary_id)
{
ProductIdentifier pi = await _context.ProductIdentifiers
.Where(i => i.Id == primary_id)
.SingleOrDefaultAsync();
ViewModelEditIdentifierInIndexView ViewModel = new ViewModelEditIdentifierInIndexView
{
SingleItem = _mapper.Map<ViewModelProductIdentifier>(pi),
ListOfItems = _mapper.Map<ICollection<ViewModelProductIdentifier>>(await _context.ProductIdentifiers.ToListAsync())
};
return View(ViewModel);
}
Then, I changed the model in the Index-view:
#model MyStore.Models.ViewModels.ViewModelEditIdentifierInIndexView
Then, I changed the edit form. The most important change is the addition of name-tags on each input-field:
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="SingleItem.Id" name="Id" />
<div class="form-group col-lg-4" style="padding-left:0px;">
<input asp-for="SingleItem.Label" name="Label" class="form-control" />
<span asp-validation-for="SingleItem.Label" class="text-danger"></span>
</div>
<div class="form-group col-lg-6" style="padding-left:0px;">
<input asp-for="SingleItem.Description" name="Description" class="form-control" />
<span asp-validation-for="SingleItem.Description" class="text-danger"></span>
</div>
<div class="form-group col-lg-1" style="padding-left:0px;">
<input asp-for="SingleItem.SortOrder" name="SortOrder" class="form-control" />
<span asp-validation-for="SingleItem.SortOrder" class="text-danger"></span>
</div>
<div class="form-group col-lg-1" style="padding-left:0px;">
<button type="submit" value="Save" class="btn btn-xs btn-success">
<span class="glyphicon glyphicon-floppy-disk"></span>
</button>
<a href="/Admin/ProductIdentifiers" class="btn btn-xs btn-warning">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
</div>
</form>
I didn't have to make any changes to the Edit method in the controller.

Categories