简体   繁体   中英

Tag Helper forms: asp-for not working as expected

Thanks for the help so far. I've worked to make sure everything else works so I can focus on this problem. I'm still convinced it'll be an easy fix once we've cracked it. I have the following code, sorry I changed it so much, I had to start again after I made a real mess of the last one without taking a backup.

        public IActionResult Index()
    {

        if(IndexModel.GlobalTasks == null)
        {
            IndexModel initModel = new IndexModel();
            initModel.AllTasks = InitList();
            initModel.EmptyTask = new ToDoTask();
            IndexModel.GlobalTasks = initModel.AllTasks;
        }
        IndexModel model = new IndexModel();
        model.AllTasks = IndexModel.GlobalTasks;
        model.EmptyTask = new ToDoTask("");
        return View(model);
    }
    //Create Task
    public IActionResult Create(ToDoTask indexModel)
    {
        IndexModel.GlobalTasks.Add(indexModel);
        return RedirectToAction("Index");
    }

And:

@model DE.Models.IndexModel
<h2>To Do List</h2>
<form asp-action="Create">
    <input asp-for="EmptyTask" value="@Model.EmptyTask" />
    <input asp-for="EmptyTask.TaskDetails" placeholder="New Task" />
    <button type="submit">Add Task</button>
</form>

The good news is this creates a new ToDoTask. So the Controller code must be pretty close to spot on. The problem is the View is passing null details to the controller, so I'm getting an empty Task, which isn't what I want. Any ideas?

在此处输入图像描述

Using Tag Helper forms:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    
<section >
    <input type="text" asp placeholder="Title" asp-for="MyWork.Title"/>
</section >

Your controller action expects a ToDoTask object while your view uses a TaskViewModel object.

Try using the same type in both of them.

In your Create() method you need to instantiate the ToDoTask object, I think. So try this:

[HttpPost]
public IActionResult Create(ToDoTask newTask)
{
    newTask = new ToDoTask(); 

    return RedirectToAction("Index");
}

You may also need to return the ToDoTask object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM