How to create an application from scratch in ASP.NET MVC?

3

I'm studying about Asp.Net MVC and here

My problem is this:

I have this form that is in Jsfiddle and that I have to add this information to a database, ie I would have to get the data - > create one Query to insert and save in the database.

I would like to understand where all the code between the Controller and the Model would go until insertion into the database.

If possible with example codes.

    
asked by anonymous 17.03.2016 / 01:05

1 answer

5

I have a better introduction to you .

  

I would like to understand where all the code between the Controller and the Model would go until insertion into the database.

Well, you just answered a part of your own question. I'm going to work out more technically.

Your form has an action , which is the same name as the Controller method. For example:

[HttpPost]
public ActionResult MinhaAcao(MeuViewModel viewModel)
{
    ...
}

Your form, in this case, would look like this:

<form id="form1" action="/MeuController/MinhaAcao">

Field names reflect what the Model or ViewModel receives. For example, your field:

<input type="text" class="form-control" id="inputNome" name="name" placeholder="Título">

% w / w of% is name , then ViewModel must have:

public class MeuViewModel
{
    public String name { get; set; } // O campo precisa ter exatamente o mesmo valor do atributo "name" do formulário
    ...
}

The assignment of the submitted values is done automatically through an ASP.NET MVC functionality called Model Binding .

In case your form is wrong because it has two "name" s with the same <input> (with, in fact, the value "name").

Assuming now that you have corrected your form and tested to send data to the Controller . If you have filled a ViewModel and you are using the Entity Framework, you will also have to fill a Model also to insert or update the information in the database, Model of the form directly. Some disagree that this is safe, so some chains discourage the use of Models directly on forms. In a nutshell, I think it's safe because there are ways to check the Model before inserting, for example using "name" .

If you are not using the Entity Framework, simply read the values from the Model or ViewModel properties and insert it into the database any way you like.

I will not lengthen the answer on the Entity Framework because it does not have to. If you want to know more, ask another question or express yourself by comments.

    
17.03.2016 / 01:19