cagdas
cagdas

Reputation: 167

Editing single entry and show multiple in ASP.NET MVC

I am very new to this and I am trying to show multiple entries to show and have a single button for each entry to edit them. I thought it would be really easy but For some reason I am not getting the clicked entity. Is there way of getting modified entity without running javascript?

Any help will be appreciated. I couldn't find any example code that does this. There are many examples that returns all the entries but not the single element.

Here is my entity class Resource:

public class Resource 
{
    [Required]
    public string title { get; set; }
    [Required]
    public int value { get; set; }
    
    [Key]
    [Required]
    public int id { get; set; }
}

On the controller side I have:

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

    [HttpPost]
    public IActionResult Index(Resource resource)
    {
        return View(resource);
    }

Here is the View and EditorTemplates

@model learningMVC.Models.Resource[]
@{
    ViewData["Title"] = "index";
}
<h1>index</h1>
<fieldset>
    @Html.EditorFor(x => x);
</fieldset>


@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@model learningMVC.Models.Resource
<div>
    First Name:<br />
        <form asp-action="Index" asp-controller="Home">
             <input asp-for="id" class="form-controller" />
             <input asp-for="value" class="form-controller" />
             <input asp-for="title" class="form-controller" />
             <input type="submit" value="Save" class="btn btn-primary" id="[email protected]" />
        </form>
</div>

Upvotes: 0

Views: 239

Answers (1)

Yinqiu
Yinqiu

Reputation: 7190

In your case, you should use particalview instead of editfor, you can see my demo below.

_ResourcesPartical.cshtml:

enter image description here

@model Resource
<div>
    <form method="post" asp-action="Index">
        First Name:<br />
        <input asp-for="id" class="form-controller" />
        <input asp-for="value" class="form-controller" />
        <input asp-for="title" class="form-controller" />
        <input type="submit" value="save" />
    </form>
</div>

Your Index view:

@model List<Resource>
@foreach(var m in Model) 
   { 
       @await Html.PartialAsync("_ResourcesPartical", m)
   }

Controller:

[HttpGet]
public IActionResult Index()
{
    //here you get your data.below is my fake data.
    var resources= new List<Resource>
    {
            new  Resource
        {
            id = 1,
            title = "aa",
            value = 3
        },
            new  Resource
        {
            id = 2,
            title = "bb",
            value = 4
        }
    };
    return View(resources);
}

[HttpPost]
public IActionResult Index(Resource resource)
{
    return RedirectToAction("Index");
}

Test result:

enter image description here

Upvotes: 1

Related Questions