Create a record and add relationship through the httpPost Web Api

Asked

Viewed 157 times

2

When creating a new record in the tab I need to take the ID of my main screen and send along with the new object. Currently I have this code:

    public async Task<IHttpActionResult> PostMenuProduct(MenuProduct MenuProduct)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.MenuProducts.Add(MenuProduct);
        await db.SaveChangesAsync();

        if (MenuProduct.MenuIdAux != null)
        {
            RelationshipMenuProductWithMenu relationship = new RelationshipMenuProductWithMenu
            {
                MenuProductId = MenuProduct.Id,
                MenuId = Convert.ToInt32(MenuProduct.MenuIdAux)
            };

            await AddRelationshipMenuProductWithMenu(relationship);
        }

        return CreatedAtRoute("DefaultApi", new { id = MenuProduct.Id }, MenuProduct);
    }

In this case I add MenuIdAux in the model to send together with the new object the id of my main screen. How I could create this relationship without having to add this parameter to my model MenuProduct? I tried to pass as parameter in the post but the HttpPost did not accept.

1 answer

1


Two ways:

1. Creating a Viewmodel identical to your Model, with one more parameter

public class MenuProductViewMode {
    public int MenuIdAux { get; set; }

    // Coloque aqui os outros parâmetros do Model
}

Mount the Model inside the method:

public async Task<IHttpActionResult> PostMenuProduct(MenuProductViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var menuProduct = new MenuProduct();
    // Faça todas as atribuições de viewModel para o seu Model aqui

    db.MenuProducts.Add(MenuProduct);
    await db.SaveChangesAsync();

    ...
}

2. Passing as Action parameter

This way is not as good as the first because the variable is free, but it works.

Put as argument the following:

public async Task<IHttpActionResult> PostMenuProduct(MenuProduct MenuProduct, int MenuIdAux) { ... }

Place a field in your upload JSON called MenuIdAux that the bind will be done automatically.

  • I should create a project to save my Viewmodels and then share them with the Web Api and the Asp.Net MVC project?

  • 1

    @Carlosgeovanio Can be done this way, or else the Viewmodels can stay in the API project and the API project be referenced by the MVC project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.