I am a programmer at asp.net core mvc, Image:
I want to do such a thing but belong by id
I was able to do the first part I add data to database and associate it with id, but can not display the messages. I will show the code I tried to do but when I try to do foreach I get NullReferenceException
My Controller:
public async Task<IActionResult> Index1()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index1(Comment comment, int id)
{
ModelState.Clear();
TryValidateModel(comment);
if (!ModelState.IsValid)
{
var animal = await _context.Animals.FindAsync(id);
comment.Animal = animal!;
_context.Add(comment);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index1));
}
return View(_context.Comments.ToList());
}
My Partial View:
@model PetShop.Data.Models.Comment
<form method="post">
<div >
<label asp-for="Content" ></label>
<input asp-for="Content" />
<span asp-validation-for="Content" ></span>
</div>
<input type="submit" value="click me"/>
My View:
@model IEnumerable<PetShop.Data.Models.Comment>
@await Html.PartialAsync("_MyPatial")
@if(Model != null)
{
foreach(var item in Model)
{
@item.Content
}
}
Note: here I do not get null because I made a condition but I want it to do and display, my problem is to only display the messages that are registered or exist in the database
CodePudding user response:
Load Animal List:
Controller:
public IActionResult Index() { var animal = _context.Animals.ToList(); return View(animal); }
View:
@model IEnumerable<MVCApps.Models.Animal> @{ ViewData["Title"] = "Index"; } <h2>Animal List</h2> <p> <a asp-action="Create">Create New</a> </p> <table > <thead> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Category) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> Animal Details </th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Category) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> <a asp-action="Details" asp-route-id="@item.AnimalId">Details</a> </td> </tr> } </tbody>
Output:
Load Animal Details:
Controller:
public ActionResult Details(int? id)
{
var objAnimal = _context.Animals.Where(aId => aId.AnimalId == id).FirstOrDefault();
AnimalViewModel _animal = new AnimalViewModel();
_animal.AnimalId = objAnimal.AnimalId;
_animal.Name = objAnimal.Name;
_animal.Category = objAnimal.Category;
_animal.Description = objAnimal.Description;
return View(_animal);
}
View Model:
public class AnimalViewModel
{
[Key]
public int AnimalId { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public string Description { get; set; }
}
View For Animal Details:
@model MVCApps.Models.AnimalViewModel
@{
ViewData["Title"] = "Details";
}
<div>
<h4><strong>Animal Details</strong> </h4>
<table >
<tr>
<th> @Html.DisplayNameFor(model => model.Name)</th>
<td> @Html.DisplayFor(model => model.Name)</td>
</tr>
<tr>
<th> @Html.DisplayNameFor(model => model.Category)</th>
<td> @Html.DisplayFor(model => model.Category)</td>
</tr>
<tr>
<th> @Html.DisplayNameFor(model => model.Description)</th>
<td> @Html.DisplayFor(model => model.Description)</td>
</tr>
</table>
<!-- TextBox Post Comment -->
<div >
<div >
<div >
<form id="postCommentByAnimalId">
<table >
<tr>
<th>
<button type="submit" >Post Comment</button>
</th>
<td>
<input type="text" id="Content" name="Content" placeholder="Enter your comment" />
<input type="text" id="AnimalId" hidden name="AnimalId" value="@Html.DisplayFor(model => model.AnimalId)" />
</td>
</tr>
<tr>
<th>
@Html.ActionLink("Back To List", "Index", new { /* id=item.PrimaryKey */ }, new { @class = "btn btn-info" })
</th>
<td>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<div >
@*This is where your comment partial view will appear appear when user hits submit on our form*@
<div id="commentDisplay"></div>
</div>
</div>
@section scripts {
<script>
//This Fucntion Load All the Comment based on Amimal Id
function LoadAllComment(animalId) {
var Comment = {
AnimalId: $("#AnimalId").val()
};
console.log(Comment);
$.ajax({
method: "POST",
url: "https://localhost:44361/Amimal/PostComment",
data: Comment,
success: function (result) {
//When then load our partial view into our containing div on the main page
$('#commentDisplay').html(result);
}
});
}
$(document).ready(function () {
//Get animal Id which List of comment need to load
var animalId = '@Html.DisplayFor(model => model.AnimalId)'
//Displaying comment for specific Animal when details button clicked
LoadAllComment(animalId);
//When the user hit the submit button we will post the form results to our partial view controller
$('#postCommentByAnimalId').submit(function () {
$.ajax({
method: "POST",
url: "https://localhost:44361/Amimal/PostComment",
data: $(this).serialize(),
success: function (result) {
//When then load our partial view into our containing div on the main page
$('#commentDisplay').html(result);
//Clear Comment Text Box after posting comment
$("#Content").val("");
}
});
return false;
});
});
</script>
}
Output:
Post Comment and Display Controller & Partial View:
Controller:
[HttpPost]
public ActionResult PostComment([Bind("Content,AnimalId")] Comment comment, int id)
{
if (comment.Content != null)
{
_context.Comments.Add(comment);
_context.SaveChanges();
ModelState.Clear();
}
List<Comment> commentList = _context.Comments.Where(cmId => cmId.AnimalId == comment.AnimalId).ToList();
return PartialView(commentList);
}
Partial View:
@model IEnumerable<MVCApps.Models.Comment>
<div >
@if (Model != null || Model.Count() < 1)
{
using (Html.BeginForm("PostComment", "Amimal", FormMethod.Post))
{
<table >
@foreach (var item in Model)
{
<tr>
<td> @item.Content <br /><input hidden name="id" value="@item.CommentId" /> </td>
</tr>
}
</table>
}
}
else
{
<p>No results found</p>
}
</div>