DEV Community

FaithInErrorsZORO
FaithInErrorsZORO

Posted on

Is this the best way to use middleware in a mvc asp.net app?

Here is program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Top comments (2)

Collapse
 
faith_in_errors_ profile image
FaithInErrorsZORO

if you want to test it try adding a controller like this

`
public class Controller : Controller
{
public IActionResult Index()
{
List ConList = new Con().GetCons();
return View(ConList);

    }
    [HttpGet]
    public IActionResult Add()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Add(Con newCon)
    {
        newCon.AddCons();
        return RedirectToAction("Index", "Con");
}
Enter fullscreen mode Exit fullscreen mode

}
`

Collapse
 
faith_in_errors_ profile image
FaithInErrorsZORO

Sorry and for your adding model I would make it like this :

`

private static List ConList = new List();

    public long ConId { get; set; }
    [Display(Name = "Con")]
    [DataType(DataType.Text)]
    public string ConName{ get; set; }

    public bool AddCons()
    {
        ConList.Add(this);
        return true;
    }
Enter fullscreen mode Exit fullscreen mode

`

and for some logic to loop through and display you'll probably want this
in your views
`

@foreach (var currentCon in Model)
{

    <div>
        @currentCon.ConName @currentCon.Time
    </div>
Enter fullscreen mode Exit fullscreen mode



@using (Html.BeginForm("Add", "Con", FormMethod.Post))
{
@html.LabelFor(m => m.ConName)
@html.EditorFor(m => m.ConName, new { htmlAttributes = new { placeholder = "ConName" } })

        @Html.LabelFor(m => m.Time)
        @Html.TextAreaFor(m => m.Time, new { placeholder = "Time" })

        <input type="submit" value=" Submit" />
    }
</fieldset>
Enter fullscreen mode Exit fullscreen mode

or the asp helpers instead :

<fieldset>
    <form asp-action="Add" asp-controller="Person">
        <label asp-for="PersonName"></label>
        <input asp-for="PersonName" placeholder="PersonName" />
        <label asp-for="Country"></label>
        <input asp-for="Country" placeholder="Country"> 
        <label asp-for="Validated"></label>
        <input asp-for="Validated" type="CheckBox">
        <label asp-for="Medals"></label>
        <input asp-for="Medals" placeholder="Medals"> 


        <input type="submit" value=" Submit" />
    </form>

</fieldset>
Enter fullscreen mode Exit fullscreen mode

`