Razor MVC -How to creat an object from a form within view?

Viewed 23

I want to create a blog and add the entries to a list. So this is my object.

    namespace MyBlog.Models {
    public class Eintrag {
        public static List<Eintrag> Eintraege { get; set; } = new();
        public string BlogEintrag { get; set; } = string.Empty;
        public string BlogName { get; set; } = string.Empty;
        public string Date { get; set; } = DateTime.Now.ToShortDateString();
        public string Title { get; set; } = string.Empty;
        public string Untertitle { get; set; } = string.Empty;
    }
}

This is the view

    @{
    ViewData["Title"] = "Eintrag verfassen";
}

<h1>Eintrag schreiben</h1>
<form action="/Home/Eintraege_anzeigen/" formmethod="get">
    <div class="form-group">
        <label for="BlogName">Blog</label>
        <input class="form-control" type="text" name="BlogName" />
    </div>
    <div class="form-group">
        <label for="Title">Titel</label>
    <input class="form-control" type="text" name="Title" />
    </div>
    <div class="form-group">
        <label for="Untertitle">Untertitel</label>
    <input class="form-control" type="text" name="Untertitle" />
    </div>
    <div class="form-group">
        <label for="eintrag">Eintrag</label>
        <textarea class="form-control" rows="5" name="BlogEintrag" id="eintrag"></textarea>
    </div>
    <input type="submit" value="SEND">
</form>

Now i want to get the object to the list, either before or after it was submited. How do i do that? something like

Eintrag.Eintraege.Add(this);
<input type="submit" value="SEND">
1 Answers

Change <form action="/Home/Eintraege_anzeigen/" formmethod="get"> into <form asp-action="Eintraege_anzeigen" method="post">

In HomeController:

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Eintraege_anzeigen(Eintrag Eintrag)
        {
            return View();
        }

result:

enter image description here

Have a look at Overview of ASP.NET Core MVC to know more.

Related