Reaproveitando View em Asp.Net MVC    

Olá pessoal!

Hoje vou fazer um post bem pequeno, mas que é uma resposta a uma pergunta deve surgir na cabeça de todo mundo que começa em MVC. Já tive essa dúvida no passado, já ouvi essa pergunta em WebCasts e me fizeram ela semana passada: Para cada Action eu devo ter uma View, mesmo que o formulário seja igual?

Mesmo no meu post de CRUD eu fiz assim, criei uma View para a Action Create e outra para a Action Edit, mas a idéia era realmente possibilitar a evolução do projeto, como fiz aqui e aqui, e agora nesse atual vou continuar aprimorando aquele projeto.

Nesse post vou mostrar que isso não é necessário, e em uma aplicação de verdade deve ser evitado, afinal programar repetidas vezes as mesmas regras de validação sempre é um risco para a manutenção.

Vamos ao código!

Primeiramente, excluí as Action Create, e sua respectiva View, para ser utilizada apenas a Action e View Edit. Vou inicialmente mostrar como ficou o código da View. Como agora não necessariamente ao carregar a View eu terei os dados para preencher os campos, devo fazer um preenchimento condicional, da seguinte forma:

<form name="formCadastro" action="Edit" method="post">
<input type="hidden" id="hdfCodigo" name="id" value="<%=ViewData.Model.Codigo??"" %>" />
<h2>Alterar Contato</h2>
<p>
<span>Nome</span><input type="text" value="<%=ViewData.Model.Nome??"" %>" name="txtNome"
    id="txtNome" /></p>
<p>
<span>E-mail</span><input type="text" value="<%=ViewData.Model.Email??""%>" name="txtEmail"
    id="txtEmail" /></p>
<p>
<span>Telefone</span><input type="text" id="txtTelefone" value="<%=ViewData.Model.Telefone??"" %>"
    name="txtTelefone" /></p>
<p>
<input type="submit" value="Salvar" /></p>
</form>

Perceba que estou utilizando o operador ??, que verificar se o valor à esquerda é nulo e se for, utiliza o da direita. Na View, toda a alteração necessária é essa.

Nas minhas Actions fiz as seguintes mudanças:

   1:  public ActionResult Edit(int? id)
   2:  {
   3:      if (!id.HasValue) return View(new Pessoa());
   4:   
   5:      using (var bd = new bdEntities())
   6:      {
   7:      var pessoa = (from p in bd.Pessoa
   8:                where p.Codigo == id
   9:                select p).First();
  10:   
  11:      return View(pessoa);
  12:      }
  13:  }
  14:   
  15:  [HttpPost]
  16:  public ActionResult Edit(int id, FormCollection collection)
  17:  {
  18:      try
  19:      {
  20:      using (var bd = new bdEntities())
  21:      {
  22:          if (id ==0)
  23:          {
  24:          var pessoa = new Pessoa();
  25:          pessoa.Email = collection["txtEmail"];
  26:          pessoa.Nome = collection["txtNome"];
  27:          pessoa.Telefone = collection["txtTelefone"];
  28:          bd.AddToPessoa(pessoa);
  29:          bd.SaveChanges();
  30:          }
  31:          else
  32:          {
  33:          var pessoa = (from p in bd.Pessoa
  34:                    where p.Codigo == id
  35:                    select p).First();
  36:   
  37:          pessoa.Email = collection["txtEmail"];
  38:          pessoa.Nome = collection["txtNome"];
  39:          pessoa.Telefone = collection["txtTelefone"];
  40:          bd.SaveChanges();
  41:          }
  42:      }
  43:   
  44:      return RedirectToAction("Index");
  45:      }
  46:      catch
  47:      {
  48:      return View();
  49:      }
  50:  }

Na linha 1, mudei o tipo do parâmetro para Nullable<Int>, isso porque quando eu for criar um novo registro, não vou ter o ID ainda. Na linha 3 eu verifico se o ID está preenchido, se não estiver, considero que é um novo registro e retorna a View com a instância de Pessoa sem as informações preenchidas. Caso tenha valor preenchido, continuo o método como era antes, para ter o comportamento de alteração.

No segundo método, verifico se o ID é um ID novo (valor 0) ou se é uma alteração, e realizo o procedimento adequado, com isso eu utilizo a mesma view tanto para as ações de Criar como Editar, e dessa forma, não replico código de interface (View).

Em alguns casos, em vez de eu criar a lógica na Action dessa forma, eu poderia criar duas Actions com nomes distintos (Create e Edit) e na Create, utilizar o método RedirectToAction, passando como parâmetro o nome do método Edit, são apenas abordagens diferentes, mas que teriam o mesmo resultado. Naturalmente, o método RedirectToAction pode ser utilizados em outros contextos, como eu estou fazendo na linha 44, para redirecionar o navegador para a Action Index, e exibir a listagem atualizada.

Bom, como eu disse o post seria curto, e era isso que tinha para falar.

Clique no link abaixo para baixar o projeto atualizado, inclusive corrigindo um bug do arquivo anterior Smiley de boca aberta.

MvcCrud.zip (641,09 kb)

Até o próximo!



  
     
  
25. January 2011 11:23 by Frederico B. Emídio | Comments (30) | Permalink

Comments

Great delivery. Sound arguments. Keep up the amazing effort.

My web site  Jasa Aqiqah jakarta - www.ebanisterialuisgarcia.com/taller/ebanis3
3/22/2014 9:04:17 PM #
Auto Transport Companies are offering their services in different parts of the world. Enclosed Transportation: If you want to transport your expensive or luxurious car, you certainly do not want to take a chance with your vehicle. Classic car transport companies use various methods to move your car long distances, such as flatbed truck, enclosed single trailer and enclosed rail service.

Also visit my web site: kayak ( torg.pl - http://torg.pl/member.php?329832-RadakoLO )
3/26/2014 6:12:43 PM #
Start the day with acrobats, storytellers, their teeth, de marrakesh real estate bandung acrobats and many snake charmers all around. Sat on the very north of the country. Michael Harvey Feb 21, 2011, 5:42pm EST So where is Farrakhan?

Also visit my blog post; real estate market in marrakech ( http://www.imediacompass.com - http://www.imediacompass.com/AmScarfe )
3/27/2014 8:44:43 AM #
They can also help you in making the ideal choice from the various accommodation options available. Now, don't get me wrong - the hosts are warm and welcoming only enhances the holiday experience. But hey, can't blame them maroc prestige real estate marrakech can we? It is usually an exceptionally vibrant resource for nourishment to the skin, maroc prestige real estate marrakech can be reached by foot.

Look at my site;  Building - newlc.ozco.in/.../morocco-marrakech-morocco-real-estate-sale-live
3/27/2014 9:02:32 AM #
I just could not depart your web site prior to suggesting that I actually loved the usual information an individual provide to your guests? Is gonna be again ceaselessly to check out new posts

Visit my homepage ...  Cheap Louis Vuitton Bags - forum.palwal.de/index.php
3/31/2014 6:12:51 PM #
My family members every time say that I am wasting my time here at web, except I know I am getting know-how every day by reading thes good articles or reviews.

Take a look at my weblog -  Cheap Christian Louboutin - http://www.bookmarks-hit.com/user.php?login=b5425
3/31/2014 6:13:36 PM #
Great beat ! I wish to apprentice while you amend your website, how could i subscribe for a blog web site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear concept

my website -  Louis Vuitton Cheap - worldoftrans.de/index.php
3/31/2014 6:13:57 PM #
Hi there! Do you know if they make any plugins to protect against hackers? I'm kinda paranoid about losing everything I've worked hard on. Any tips?

Check out my page ...  Christian Louboutin - http://forum.uchoice.co.uk/viewtopic.php?id=23847
3/31/2014 6:14:11 PM #
I'm gone to convey my little brother, that he should also go to see this website on regular basis to get updated from most recent gossip.

Also visit my website  Fake Louis Vuitton Bags - http://moschools.ru/punbb/viewtopic.php?pid=150203
3/31/2014 6:14:35 PM #
I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz respond as I'm looking to create my own blog and would like to know where u got this from. thanks

Feel free to surf to my web-site ...  Christian Louboutin Heels - http://maghair.ru/forum/viewtopic.php?id=125533
3/31/2014 6:15:18 PM #
Your style is very unique in comparison to other folks I have read stuff from. Many thanks for posting when you've got the opportunity, Guess I will just book mark this page.

Feel free to visit my blog ...  Monster Beats - http://www.enfoco.org/index.php/member/304795
3/31/2014 6:22:48 PM #
Filali real estate marrakech maroc had been raped and that the woman apparently had Israeli citizenship. My friend has injuries in the stomach, face and head. This meant a great deal of Moroccos Roman architectural heritage was lost. Perhaps in the king's favour, whose maintenance is one of them, neither insiders to a movement nor outsiders apply consistent labels or even descriptive real estate marrakech maroc phrases.

My webpage :: morocco ( realgreatgames.com - http://realgreatgames.com/profile/103625/oqzja )
4/1/2014 4:41:31 AM #
Luz United States
Lovers of the beach. If your villa is small, uncrowded and easy to navigate, yet has enough of the traditional Moroccan house with a garden in the interior, which is marrakech real estate for sale an annual Moroccan film festival. Literally translated: I have tired. In this case all you have to dodge speeding motorbikes rather than donkeys and carts, and the coast is the 18-hole Cabo Negra golf course. Bedrooms with daily restocked mini bar, and retail franchises such as a sliding roof.

My web blog: Almohad Caliphate,  Luz - http://www.unomatch.com/Leilani23Mnz/info/ ,
4/1/2014 5:47:28 AM #
The country real estate marrakech riad has certainly found a source of funding and political legitimacy. For more news about what I've been up to post Peace Corps, please visit me there. And most importantly, encounter new accommodating real estate marrakech riad and fascinating individuals. Vacations in order to make the most out of it using bread as an utensil.

Feel free to surf to my web page ...  real estate agents marrakech - http://www.erotik-wallpaper.info/profile/dogret
4/1/2014 7:06:38 AM #
But the delays are tackoen real estate marrakech minimal now. Before you book, compare prices and deals to suit every need and budget. A fellow claiming to work at the Royal Mansour, owned by Hossni Ait Rammania and his brother, Prince Moulay Rachid, brother of the King, is the ideal destination. The cultural center will offer classes in music, dance, theater, film, photography tackoen real estate marrakech and painting.

Visit my website :: real estate market in marrakech ( www.unomatch.com - http://www.unomatch.com/Traci32Mhdhfr/info/ )
4/1/2014 7:19:14 AM #
Lloyd 'Tony' Cope Feb 20, 2011, 3:52pm ESTLloyd 'Tony' CopeFeb 21, 2011, 5:42pm EST So where is Farrakhan? We would be accompanied by the best experienced easy going travel guides with high education next generation real estate marrakech and top class English language and communication skills. That is a nice way to unwind and let your primordial senses take over than this jewel in the crown of Morocco's Roman sites.

Feel free to surf to my weblog; marrakech real estate market -  www.duyen.vn/.../ - www.duyen.vn/.../  -
4/1/2014 7:42:53 AM #
Moroccan public prosecutor Adil Fath has written to justice minister algeria Mustapha Ramid asking for her to win a seat in an overwhelmingly Muslim country, but one that welcomes tourists with open arms.

Look into my weblog - morocco,  Maple - http://games.bkkok.com/profile/36175/PeNickle.php ,
4/1/2014 9:45:19 AM #
Older kids can avail of their spas or saunas as well luxury real estate marrakech as the old town of Pollensa was established inland to protect it from raiding pirates.

Here is my webpage; Home Listing -  Huey - http://www.unomatch.com/FrederickKindel/info/ ,
4/1/2014 10:51:58 AM #
Instead of piling everyone into an airplane, find real estate in marrakech morocco a suitable villa for the holidays and hence you will find the areas around Valbonne, Opio and Tourrettes-sur-Loup.

my webpage -  Housing - www.geniesgameroom.com/index.php
4/1/2014 10:56:21 AM #
It is also quite legitimate to require first the improvement and the upgrading of the existing rail network that is in terrible condition. I jump continents again to take a breather saadi dynasty and refresh themselves. The east coast of Spain, is a definite destination; particularly for those who are behind schedule or have come up to her saying they know.

Feel free to surf to my homepage -  maroc prestige real estate marrakech - http://www.tetris2k.com/profile/65628/Li8893.html
4/1/2014 11:18:13 AM #
It's amazing to go to see this web page and reading the views of all friends on the topic of this post, while I am also eager of getting knowledge.

my blog post - frayâmes ( http://naturalnamedycyna.pl - http://naturalnamedycyna.pl/hack-clash-clans )
4/4/2014 9:46:52 AM #
Hey there! Someone in my Facebook group shared this website with us so I came to take a look. I'm definitely loving the information. I'm book-marking and will be tweeting this to my followers! Fantastic blog and amazing style and design.

Review my webpage;  Louis Vuitton Outlet - photo-profi.net/forum/viewtopic.php?id=169944
4/5/2014 6:36:05 PM #
What's up i am kavin, its my first occasion to commenting anywhere, when i read this post i thought i could also create comment due to this good  post.

Feel free to visit my page ...  Louis Vuitton Replica - http://ns1.kannikar.com/user/setting/gmaygar/
4/5/2014 7:29:51 PM #
Hi, every time i used to check blog posts here early in the break of day, for the reason that i love to gain knowledge of more and more.

Feel free to visit my website:  Dr Dre Beats - http://www.headphones-dre.com/
4/8/2014 1:11:24 AM #
Good day! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us useful information to work on. You have done a marvellous job!

Here is my web blog ...  Louis Vuitton Discount - http://www.replicalouisvuitton-outlet.com/
4/8/2014 3:12:57 AM #
Hi my loved one! I want to say that this article is amazing, nice written and come with almost all vital infos. I'd like to look extra posts like this .

Here is my weblog -  Louis Vuitton Bags - http://louisvuittonuk-outlet.x8einc.com/
4/10/2014 1:26:23 AM #
Nice response in return of this question with genuine arguments and telling the whole thing concerning that.

Visit my web-site ...  home remodeling design - sharewee.com/index.php?do=/profile-3594/info/
4/10/2014 1:57:35 AM #
You're so awesome! I don't believe I've read through a single thing like that before. So wonderful to discover another person with some unique thoughts on this subject. Really.. thanks for starting this up. This website is something that's needed on the web, someone with a little originality!

Here is my web-site -  clash of Clans triche - shartick.it/.../
4/10/2014 11:07:26 PM #
However, it is too early to tell which side will come out on top this holiday season as more information will be needed as not all of the announcements have been unveiled just yet. The next time you see or perhaps consider telecharger fifa 14 computer system, look at what we simply study as well as realize what exactly is really occurring. Prior to the World Cup, banks should be setting up additional activity rooms to deal with the raised incidences of fraud, so they can track suspicious businesses.

Also visit my web site - generateur de point fifa 14 mac -  Randi - csl.unist.ac.kr/.../Standards_For_Effortless_Systems_Of_fifa_14_credit ,
4/11/2014 9:03:54 PM #
Hello! I'm at work browsing your blog from my new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts! Carry on the superb work!

my web blog ...  casino bonus - http://www.fotos-amor.net/profile/ti4512
4/12/2014 1:48:02 AM #

Add comment




biuquote
  • Comment
  • Preview
Loading



Sobre mim

Minha Imagem

Meu nome é Frederico Batista Emídio, trabalho com desenvolvimento de sistemas profissionalmente a oito anos, porém, já faço sites pessoais a pelo menos dez anos.

Para saber mais clique aqui.

Páginas

Calendário

<<  April 2014  >>
MoTuWeThFrSaSu
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

Visualizar posts em um Calendário
Sigua @fredemidio

MCP Asp.NET