Korpin
Korpin

Reputation: 325

Passing a IEnumerable<Model> to my View to show the result

First, I'd like to point out that I'm using .NET Core with MVC.

I have a method (GetMember) of the async Task <IActionResult> type of my Members controller that receives an id (the id of the user) and sends it to an external database (via Filemaker API).
In return, I receive an IEnumerable that contains my result. (Until then everything is fine, it works perfectly).

My problem is that I can not put this data in my view.
Indeed, I have a form and I would like the data received to be automatically entered in my form.

My problem results in passing my variable results to my model, I can not find how to send data from one to another.

I know however to use the data of my existing model Members, but if you want I can add the code of the view.

I deliberately deleted the piece of code that is supposed to perform this operation because the result was wrong.

Could you give me a hand?

EDIT/ with code refreshed, i now receive an error 500 on Chrome when i open the page... any idea?

Controller

[HttpGet]
    public async Task<IActionResult> GetMember(int? id)
    {
        if(id == null)
        {
            return NotFound();
        }

        try
        {
        FileMakerRestClient client = new FileMakerRestClient("https://fms171.hostmy.solutions", "helloJAK", "jak", "legeneral!");
        var toFind = new Models.Members { Zkp_WEB = id };
        var results = await client.FindAsync(toFind);

            bool isEmpty = !results.Any();
            if (isEmpty)
            {
                return NotFound();
            }

        return View(results);
        }
        catch
        {
            return BadRequest();
        }
    }

View

<script type="text/javascript">

    $(document).ready(function () {
        GetMember();

    }); 

        function GetMember() {
            $.ajax({
                url: "https://localhost:44338/Members/GetMember/" + 28
            });
    }

</script>

Upvotes: 1

Views: 616

Answers (1)

mafirat
mafirat

Reputation: 287

I don't quite understand what are you trying. But I guess you have some problem getting form data from the view. You need two action method for this; one for GET method and another one for POST method. In controller:

public async Task<IActionResult> Method()
{ 
   return View();
}

[HttpPost]
public async Task<IActionResult> Method(Model model)
{ 
   if (ModelState.IsValid)
   {
     // work with the model
   } else return View(model)
}

In View:

@model Model

<form asp-action="ActionName" method="post"> 
   <div> 
     <label asp-for = "Name"></label> 
     <input asp-for = "Name" /> 
     <span asp-validation-for = "Name"></span> 
   </div> 
   <div> 
     <input type = "submit" value = "Save" /> 
   </div> 
 </form>

You should look at this tutorial. https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/?view=aspnetcore-2.1

Upvotes: 1

Related Questions