My create.cshtml view page not opening ASP.NET Core 6 MVC application in Visual Studio 2022 - asp.net-core-mvc

I am creating an ASP.NET Core 6 MVC application, the application runs successfully but whenever I want to add an actor (based on project) the create view page does not work. It's showing an internal server error.
This is the error I get:
AspNetCoreGeneratedDocument.Views_Actors_Create.ExecuteAsync() in Create.cshtml
#model Actor
#{
ViewData["Title"] = "Add New Actor";
}
<div class="row text">
<div class="col-md-8 offset-2">
<p>
<h1>Add New Actor</h1>
The error is being highlighted on the ViewData line.
My create.cshtml
#model Actor
#{
ViewData["Title"] = "Add New Actor";
}
<div class="row text">
<div class="col-md-8 offset-2">
<p>
<h1>Add New Actor</h1>
</p>
<div class="row">
<div class="col-md-8 offset-2">
<form class="row" asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="mb-3">
<label asp-for="ProfilePictureURL" class="form-label"></label>
<input asp-for="ProfilePictureURL" type="text" class="form-control"/>
<span asp-validation-for="ProfilePictureURL" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="FullName" class="form-label"></label>
<input asp-for="FullName" type="text" class="form-control"/>
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Bio" class="form-label"></label>
<input asp-for="Bio" type="text" class="form-control"/>
<span asp-validation-for="Bio" class="text-danger"></span>
</div>
<div class="mb-3">
<input type="submit" value="Create" class="btn btn-outline-success float-end"/>
<a class="btn btn-outline-secondary" asp-action="Index"> Show All</a>
</div>
</form>
</div>
</div>
</div>
</div>
This is my ActorsController.cs:
using eTickets.Data;
using eTickets.Data.Services;
using Microsoft.AspNetCore.Mvc;
namespace eTickets.Controllers
{
public class ActorsController : Controller
{
private readonly IActorsService _service;
public ActorsController(IActorsService service)
{
_service = service;
}
public async Task<IActionResult> Index()
{
IEnumerable<Models.Actor>? data = await _service.GetAll();
return View(data);
}
public IActionResult Create()
{
return View();
}
}
}
I am using .NET 6 and Visual Studio version 17.2.5.
What could be the problem? Thanks in advance

Related

How to solve erroe 428C9 in ASP.NET Core MVC?

I made a new function for my website.It can do the job like save as.
And it can work will.
But when I create a new project, it suddenly can't work,and show the error 428C9.
What should I do? Can someone give me advice?
It is .cshtml
<div class="row">
<div class="col-xl-10">
<form asp-action="Saveas">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="IpAddress" class="control-label"></label>
<input asp-for="IpAddress" class="form-control" />
<span asp-validation-for="IpAddress" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Protocol" class="control-label"></label>
<input asp-for="Protocol" class="form-control" />
<span asp-validation-for="Protocol" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ToolHostPort" class="control-label"></label>
<input asp-for="ToolHostPort" class="form-control" />
<span asp-validation-for="ToolHostPort" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ToolSvid" class="control-label"></label>
<input asp-for="ToolSvid" class="form-control" />
<span asp-validation-for="ToolSvid" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Pid" class="control-label"></label>
<input asp-for="Pid" class="form-control" />
<span asp-validation-for="Pid" class="text-danger"></span>
</div>
<input type="hidden" asp-for="Pid" />
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
It is controller
public async Task<IActionResult> Saveas(int? id)
{
if (id == null)
{
return NotFound();
}
var gatewaySettingCloud = await _context.GatewaySettingClouds.FindAsync(id);
if (gatewaySettingCloud == null)
{
return NotFound();
}
return View(gatewaySettingCloud);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Saveas([Bind("Ipaddress,Protocol,Toolhostport,Toolsvid,Pid")] GatewaySettingCloud gatewaySettingCloud)
{
if (ModelState.IsValid)
{
_context.Add(gatewaySettingCloud);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(gatewaySettingCloud);
}
I find the database does not accept from applications, so I create a new column replace original column which one can't accept data from applications.Then I can insert the data successful!!
Helper:Karl-Johan Sjögren、Tiny Wang

ASP.NET Core MVC app : I want to show the same view after submit and render the same data but having problems

I am new to ASP.NET Core MVC but I do have some experience working with ASP.NET webforms. I am creating an ASP.NET Core MVC project for practice in this I have a controller which has [http post] Create and Http Get Create action methods.
When user is on the Create page after entering the data user can click the submit button and once the data is saved, the view for http post Create() is render (reloading same view) and I am trying to show the data that user has filled prior to submit but data is not binding to the input controls. I am passing the same model to the view which was sent to be saved. During the debug and I am able to see the expected value under the Locals window in Visual Studio.
I want to understand what I am doing wrong or what changes I should be doing in order to work. If I need to take the different approach then why this the approach (mentioned below in code) I am taking is not correct?
Below is the code and explanation in the comments.
[HttpGet]
public async Task<IActionResult> Create()
{
// I am creating a viewModel object because wanted to include the logic for List<users> for dropdown.
var createView = await _chloramine.ChloramineSaveViewModel();
return View(createView);
}
[HttpPost]
// At page submit this Action method is called and data is saved.
public async Task<IActionResult> Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
{
_chloramine.CreateChloramineLog(clEditSaveViewModel);
// After data is saved I am adding a user list to the model because I was getting Object null error.
clEditSaveViewModel.User = await _chloramine.GetUser();
// Passing the same model object which was received in order to show what was filled or selected by the user.
return View(clEditSaveViewModel);
}
Below is the Create view html.
#model EquipmentMVC.Models.ChloramineLogEditSaveViewModel
#{
ViewData["Title"] = "Create";
}
<hr />
<div>
<form asp-action="Create">
<div class="form-group row">
#foreach (var item in Model.User)
{
#Html.HiddenFor(model => item)
}
<label asp-for="TimeDue" class="col-sm-2 col-form-label control-label"></label>
<div class="col-sm-8">
<input asp-for="TimeDue" value="" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="PostPrimaryCarbanTankTp1" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="PostPrimaryCarbanTankTp1" />
</label>
</div>
</div>
</div>
<div class="form-group row">
<label asp-for="Comments" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input asp-for="Comments" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="IsCompleted" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<input class="form-check-input" asp-for="IsCompleted" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Technician</label>
<div class="col-sm-8">
<select asp-for="Selected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
#*<span asp-validation-for="Selected" class="text-danger"></span>*#
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">RN</label>
<div class="col-sm-8">
<select asp-for="RnSelected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input type="submit" value="Create" class="btn btn-secondary" />
</div>
</div>
<div><span asp-validation-for="TimeDue" class="text-danger"></span></div>
<div><span asp-validation-for="Comments" class="text-danger"></span></div>
<div><span asp-validation-for="IsCompleted" class="text-danger"></span></div>
</form>
</div>
I tested your code and found that it runs very well in my project.
Except for TimeDue, the field is not successfully bound, the rest of the fields are bound successfully.
I don’t know if you have the same problem. The TimeDue is not successful binding is because you set the Value in the view.
Please delete the value in this field in the view:
<input asp-for="TimeDue" class="form-control" />
Result:
By the way,your User is null only because your User is not successfully bound, you can modify your loop code as follows:
#for (int i = 0; i < Model.User.Count(); i++)
{
<input type="hidden" name="User[#i].Id" value=#Model.User[i].Id />
<input type="hidden" name="User[#i].Name" value=#Model.User[i].Name />
}
Then in your Create action:
[HttpPost]
public IActionResult Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
{
return View(clEditSaveViewModel);
}
Result:
Edit:
My codes:
Controller:
public IActionResult Create()
{
var model = new ChloramineLogEditSaveViewModel
{
Id = 1,
Comments = "aaaa",
PostPrimaryCarbanTankTp1 = "fjsdgk",
TimeDue = "bbbbbb",
IsCompleted=true,
RnSelected="gggg",
Selected="sgs",
User=new List<User>
{
new User{
Id=1,
Name="aa"
},
new User
{
Id=2,
Name="bb"
}
}
};
return View(model);
}
[HttpPost]
public IActionResult Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
{
return View(clEditSaveViewModel);
}
View:
<form asp-action="Create">
<div class="form-group row">
#for (int i = 0; i < Model.User.Count(); i++)
{
<input type="hidden" name="User[#i].Id" value=#Model.User[i].Id />
<input type="hidden" name="User[#i].Name" value=#Model.User[i].Name />
}
<label asp-for="TimeDue" class="col-sm-2 col-form-label control-label"></label>
<div class="col-sm-8">
<input asp-for="TimeDue" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="PostPrimaryCarbanTankTp1" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="PostPrimaryCarbanTankTp1" />
</label>
</div>
</div>
</div>
<div class="form-group row">
<label asp-for="Comments" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input asp-for="Comments" class="form-control" />
</div>
</div>
<div class="form-group row">
<label asp-for="IsCompleted" class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<div class="form-check">
<input class="form-check-input" asp-for="IsCompleted" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Technician</label>
<div class="col-sm-8">
<select asp-for="Selected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">RN</label>
<div class="col-sm-8">
<select asp-for="RnSelected" asp-items=#(new SelectList(Model.User,"Id","Name"))>
<option value="">Select...</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-8">
<input type="submit" value="Create" class="btn btn-secondary" />
</div>
</div>
<div><span asp-validation-for="TimeDue" class="text-danger"></span></div>
<div><span asp-validation-for="Comments" class="text-danger"></span></div>
<div><span asp-validation-for="IsCompleted" class="text-danger"></span></div>
</form>

Partial view update on ajax POST redirecting to form's action method

I have created 2 partial views called _ftpsetupDetails.cshtml and _ftpsetupedit.cshtml
On load of the index page i am loading details partial view onto the below div.
now the problem is on post to the controller after save i am returning the ready only mode detail partial view. But instead of loading the partial view or hit done method of ajax it is redirecing the page to /FT/Edit url with detail partial view html on it. How to make sure the page is not redirected? what am i doing wrong?
//Once user clicks on Save button the below code will post the form data to controller
$(document).on("click", "#updateFTP", function () {
$.post("/Ftp/Edit", $('form').serialize())
.done(function (response) {
alert(response.responseText);
});
});
//On page load i am loading the partialview container witih read only view
LoadAjaxPage("/Ftp/DetailsByOrgId", "organizationId=" + orgId + "&orgType=" + orgType, "#ftpPartialViewContainer");
//On edit button click i am loading the same div container with edit partial view
$(document).on("click", "#editFTP", function () {
// $("#createUserPartialViewContainer").load("/Users/Create?organizationId=" + orgId + "&organizationType=" + orgTypeId);
LoadAjaxPage("/Ftp/Edit", "organizationId=" + orgId + "&orgType=" + orgType, "#ftpPartialViewContainer");
});
<div id="ftpPartialViewContainer">
</div>
<!--Details HTML partial view code-->
<div class="card shadow mb-3">
<div class="card-header">
<p class="text-primary m-0 font-weight-bold"> FTP Setup</p>
</div>
<div class="card-body">
<div class="row">
<div class="col">
<label for="Name" class="control-label">Name</label>
<input asp-for="Name" class="form-control" readonly />
</div>
</div>
<div class="row">
<div class="col">
<label for="Password" class="control-label">Password</label>
<input asp-for="Password" class="form-control" readonly />
</div>
</div>
<div class="row">
<div class="col">
<input type="submit" value="Edit" class="btn btn-primary" id="editFTP" />
</div>
</div>
</div>
</div>
<!--Edit HTML partial view code-->
#model MyProject.Models.Ftp
#if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
#using (Html.BeginForm("Edit", "ftp", FormMethod.Post,))
{
#Html.ValidationSummary(true, "Please fix the errors")
<div class="card shadow mb-3">
<div class="card-header">
<p class="text-primary m-0 font-weight-bold"> FTP Setup</p>
</div>
<div class="card-body">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Pkid" />
<input type="hidden" asp-for="ConnectedTo" />
<input type="hidden" asp-for="ConnectedToType" />
<div class="row">
<div class="col">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="col">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary " id="updateFTP" />
</div>
</form>
</div>
</div>
}

01/01/0001 when passing birth date to control

I want to save a register form and must save birth date in another format.
In model I have:
public DateTime BirthDate { get; set; }
In the view:
#model Univer.Model.KarApplicant
#{
ViewData["Title"] = "";
}
<div class="container MainMiddle" style="padding-top:50px;">
<hr />
<div class="row container-fluid">
<div class="col-md-10">
<form asp-action="Register">
<div asp-validation-summary="ModelOnly" class="text-danger">
</div>
<div class="form-row">
....
<div class="form-group col-md-4">
<label asp-for="BirthDate" class="control-label"></label>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-calendar-alt"></i></div>
</div>
<input asp-for="BirthDate" class="form-control example1" data-val="false" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
</div>
</div>
....
<div class="form-row">
</div>
<div class="form-group float-left">
<input type="submit" value="next" class="btn btn-lg btn-primary btn-block" />
</div>
</div>
</form>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/lib/persian-date/persian-date.js"></script>
<script src="~/lib/persian-datepicker/js/persian-datepicker.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".example1").pDatepicker();
});
</script>
}
When I click on Submit button and send data to action of controller, with breakpoint check form value that pass to controller, birth dates value that are passed to controller is 01/01/0001 but I have value in persian mode in input in view.
My question is: why when set value with javascript in input and send to controller the value doesn't get sent?
UPDATE: after the comment i Added this code
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("fa-IR");
}); .....
}
and
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{....
app.UseRequestLocalization();
app.UseMvc()....
}

FormCollection parameter is empty while using #Ajax.BeginForm and html5 controls

I'm developing ASP.NET MVC5 project with boostrap, jquery, jquery UI. Submit is working fine but FormCollection in create Action is arriving empty in HomeController. I don't know what I'm doing wrong or is missing. PLease need help. Below snippet code.
Index.cshtml:
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Empleado</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Home", new AjaxOptions() { HttpMethod = "post" }, new { id = "dialog", name = "dialog" }))
{
<div class="panel">
<div class="panel-body">
<div class="form-group">
<label class="control-label">Nombres</label>
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
</div>
<div class="form-group">
<label class="control-label">Apellidos</label>
<input type="text" class="form-control" id="modalApellidos" placeholder="Apellidos" />
</div>
<div class="form-group">
<label class="control-label">Fecha de Nacimiento</label>
<input type="text" class="form-control" id="modalFechaNacimiento" placeholder="Fecha Nacimiento" />
</div>
<div class="form-group">
<label class="control-label">Tipo Documento</label>
<select class="form-control" id="modalTipoDocumento">
<option class="placeholder" selected disabled value="">--- Seleccione ---</option>
#foreach (var item in ViewBag.TiposDocumento)
{
<option value="#item.Id">#item.Descripcion</option>
}
</select>
</div>
<div class="form-group">
<label class="control-label">Número de Documento</label>
<input type="text" class="form-control" id="modalNumeroDocumento" placeholder="Número Documento" />
</div>
</div>
<div class="panel-footer">
<button type="button" role="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" role="button" class="btn btn-primary" id="btnGrabar">Grabar</button>
</div>
</div>
}
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
HomeController is:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
string nombres = collection["modalNombres"];
return RedirectToAction("Index");
}
catch
{
return View();
}
}
None of you <input> elements have name attributes so there is nothing sent to the server. Change
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
to
<input type="text" class="form-control" name="modalNombres" placeholder="Nombres" />
There is no need for id attributes unless you using javascript/jquery to refer to them.
However, I very strongly recommend you go to the MVC site and work through some basic tutorials and learn how to generate a view in MVC. You should have a model, use the strongly typed html helpers to bind to the properties of your model, and the POST method should have a parameter for the model so it is bound (you should never use FormCollection in MVC)
Note also, you using Ajax.BeginForm() which uses ajax to post the form values so return RedirectToAction("Index"); in your POST method is pointless. Ajax calls stay on the same page, they do not redirect.

Resources