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 (42) | Permalink

Comments

Fascinating blog! Is your theme custom made or did you download it from somewhere? A theme like yours with a few simple tweeks would really make my blog shine. Please let me know where you got your theme. Bless you

Feel free to visit my web site ::  creative cloud free download - www.dailymotion.com/.../x20k12v_photoshop-cc-crack-download-full-crack_tech
8/19/2014 8:20:59 PM #
Wow, this article is good, my younger sister is analyzing such things, so I am going to inform her.

Here is my page - Hay Day Astuces -  Deanna - gk.himangshu.in/index.php?title=Great_depth_-  -
8/20/2014 6:16:14 AM #
I am really impressed with your writing skills as well as with the layout on your weblog. Is this a paid theme or did you customize it yourself? Either way keep up the excellent quality writing, it is rare to see a great blog like this one today.

Here is my blog -  voyance gratuite - http://www.secretvoyance.eu
8/20/2014 12:35:12 PM #
The other day, while I was at work, my cousin stole my iphone and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views. I know this is entirely off topic but I had to share it with someone!

Take a look at my webpage ...  air ambulance transport company reviews - http://www.youtube.com/watch?v=GszBtTgfELc
8/20/2014 8:18:31 PM #
This site truly has all of the information I needed concerning this subject and didn't know who to ask.

Feel free to surf to my page ::  criminal Defense attorney miami - http://railone.kr/xe/?document_srl=640464
8/20/2014 11:50:30 PM #
Bring 2 cups of water to a boil and add the red quinoa. Cayenne, a natural phytonutrient derived from capsicum, helps support circulation. No wonder that Spirulina, has been declared by World Health Organization (WHO) as.

Feel free to visit my webpage:  Chris Ashenden my company - http://ireport.cnn.com/docs/DOC-529258
8/21/2014 4:18:23 AM #
I know this if off topic but I'm looking into starting my own blog and was curious what all is needed to get set up? I'm assuming having a blog like yours would cost a pretty penny? I'm not very web savvy so I'm not 100% certain. Any tips or advice would be greatly appreciated. Many thanks

Here is my homepage ...  Cookie Jam Cheats - http://Cookiejamcheats.Wordpress.com/
8/21/2014 5:11:31 AM #
Please let me know if you're looking for a writer for your blog. You have some really great posts and I feel I would be a good asset. If you ever want to take some of the load off, I'd love to write some content for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Thank you!

Also visit my web blog ::  vedic math - vedicmathsvideos.wordpress.com/.../
8/21/2014 7:43:13 AM #
Hello There. I found your blog using msn. This is a very well written article. I will be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I will definitely return.

Also visit my homepage :: reduce back pain ( Lucille - www.angieslist.com/.../...itute-reviews-615009.htm )
8/21/2014 8:10:29 AM #
I’m not that much of a online reader to be honest but your blogs really nice, keep it up! I'll go ahead and bookmark your website to come back down the road. Many thanks

Feel free to visit my web page ::  The Last Hurrah: the Ultimate Super Bowl Party Planner pdf - http://jadebrodyn.soup.io
8/21/2014 1:23:58 PM #
I am sure this piece of writing has touched all the internet people, its really really pleasant article on building up new webpage.

My website ...  african mango supplement - Bdl2.com.br/upload/index.php?do=/profile-453/info/
8/21/2014 10:29:05 PM #
I like what you guys are usually up too. This type of clever work and reporting! Keep up the great works guys I've added you guys to  blogroll.

Here is my blog -  african Mango capsules - http://urlaap.nl/africanmangodietpills143024
8/21/2014 10:31:01 PM #
Hello there,  You have done a fantastic job. I'll definitely digg it and personally suggest to my friends. I'm sure they will be benefited from this website.

Here is my blog ... best african mango;  Madelaine - http://X1b.it/naturalweightlosssupplements367723 ,
8/21/2014 10:48:05 PM #
Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a little bit, but instead of that, this is fantastic blog. An excellent read. I will definitely be back.

Also visit my blog post ::  garcinia cambogia pills - http://Hiphop360Sa.com/store/?q=node/28769
8/21/2014 11:43:40 PM #
Hiya very nice blog!! Man .. Excellent .. Amazing .. I'll bookmark your blog and take the feeds additionally? I'm happy to find so many useful information here in the submit, we'd like develop extra techniques in this regard, thank you for sharing. . . . . .

my web blog; african mango extract ( Chong - http://djex.co/africanmangodietpills699940 )
8/22/2014 12:02:12 AM #
May I just say what a comfort to find somebody who genuinely understands what they're discussing online. You definitely realize how to bring a problem to light and make it important. More and more people must check this out and understand this side of the story. I can't believe you aren't more popular because you most certainly have the gift.

My webpage;  garcinia cambogia pills - truyen.meximas.com/index.php?do=/profile-293/info/
8/22/2014 3:09:07 AM #
You've made some really good points there. I checked on the net for more information about the issue and found most people will go along with your views on this website.

Also visit my webpage ::  garcinia cambogia weight loss reviews - Procli.ma/puregarciniacambogiaextractreviews22696+
8/22/2014 5:26:01 AM #
I every time emailed this web site post page to all my friends, since if like to read it after that my friends will too.

my web site  Garcinia Cambogia pills - Mycuckoldress.com/.../
8/22/2014 5:26:01 AM #
After looking at a few of the blog articles on your blog, I honestly like your technique of writing a blog. I book-marked it to my bookmark site list and will be checking back in the near future. Please check out my web site as well and let me know your opinion.

Visit my homepage:  where can you buy garcinia cambogia - home.Zwoniu.com/space.php
8/22/2014 6:05:11 AM #
Excellent post. I was checking continuously this blog and I'm impressed! Extremely helpful information specially the last part Smile I care for such information a lot. I was seeking this certain info for a long time. Thank you and best of luck.

Here is my web page ...  garcinia cambogia hca - Wiki.The-Planetoid-Series.com/index.php?title=User:FedericCespedes
8/22/2014 8:06:25 AM #
Thank you a lot for sharing this with all folks you really understand what you're talking about! Bookmarked. Please additionally discuss with my site =). We will have a link exchange contract among us

Here is my site:  garcinia cambogia pills - Canimpact.org/.../
8/22/2014 8:40:28 AM #
Hi would you mind stating which blog platform you're working with? I'm planning to start my own blog soon but I'm having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I'm looking for something unique.                  P.S Sorry for getting off-topic but I had to ask!

Also visit my web-site  african mango weight loss pills - http://Go.Utau.me/africanmangoreviews903257
8/22/2014 11:04:05 AM #
Ted United States
Good day! I simply wish to offer you a big thumbs up for the excellent information you have got right here on this post. I am returning to your blog for more soon.

Also visit my homepage ... hoodia [ Ted - weshouldsearch.com/cambogia_garcinia_extract_7946174 ]
8/22/2014 11:58:25 AM #
When I initially left a comment I appear to have clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the exact same comment. Perhaps there is a way you can remove me from that service? Thanks a lot!

Also visit my website -  how much is garcinia cambogia - http://www.Kidwellconcepts.com/?p=1394
8/22/2014 12:32:25 PM #
Its such as you learn my thoughts! You appear to understand so much approximately this, such as you wrote the e-book in it or something. I think that you can do with some p.c. to force the message house a little bit, but other than that, that is fantastic blog. A great read. I will definitely be back.

my web page;  African Mango reviews - www.dom-Rukami.ru/.../311381.html
8/22/2014 2:43:56 PM #
We absolutely love your blog and find the majority of your post's to be exactly I'm looking for. Would you offer guest writers to write content available for you? I wouldn't mind creating a post or elaborating on a few of the subjects you write in relation to here. Again, awesome web log!

Feel free to surf to my web site  cambogia garcinia extract - www.Bbwconnections.com/.../
8/22/2014 3:08:36 PM #
bookmarked!!, I love your site!

My blog:  voyance gratuite en ligne - http://www.voyancetarots.com
8/22/2014 5:31:34 PM #
Heya! 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 outstanding work!

My web site;  voyance - www.familydentalassoc.net/.../Default.aspx
8/22/2014 7:06:20 PM #
These are in fact wonderful ideas in on the topic of blogging. You have touched some pleasant things here. Any way keep up wrinting.

My web site;  isosensuals - www.anime4f.com/.../...va-sealed-sword-frenzy.html
8/22/2014 8:51:51 PM #
Thanks for your marvelous posting! I actually enjoyed reading it, you might be a great author.I will make certain to bookmark your blog and will often come back sometime soon. I want to encourage you to ultimately continue your great work, have a nice holiday weekend!

Feel free to visit my web blog wp life ( http://ndreaming.com/xe/?document_srl=1406418 - http://ndreaming.com/xe/?document_srl=1406418 )
8/22/2014 11:34:30 PM #
I do agree with all the concepts you've introduced for your post. They're really convincing and can definitely work. Nonetheless, the posts are very short for beginners. May you please prolong them a little from next time? Thanks for the post.

my page; weighing things -  Katrina - http://www.fergusdoyle.ie/?p=673786 ,
8/22/2014 11:35:53 PM #
After going over a few of the blog posts on your web page, I really appreciate your way of writing a blog. I book marked it to my bookmark website list and will be checking back in the near future. Please visit my web site too and let me know what you think.

Also visit my web-site ...  ABUSED pdf - http://fcarlossophie.blog.interia.pl
8/22/2014 11:38:58 PM #
@ United States
Amazing! This blog looks exactly like my old one! It's on a totally different subject but it has pretty much the same page layout and design. Outstanding choice of colors!

Also visit my blog post ...  @ - http://angelicaellisa.blog.interia.pl
8/23/2014 12:46:06 AM #
Howdy! This blog post could not be written much better! Going through this article reminds me of my previous roommate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a very good read. Thanks for sharing!

my page ...  download ebook pdf - http://acarmeloisabella.blog.interia.pl
8/23/2014 3:50:33 AM #
@ United States
Very rapidly this web site will be famous amid all blogging visitors, due to it's pleasant articles or reviews

My web blog:  @ - http://ffredyaddie.soup.io
8/23/2014 3:51:35 AM #
It's an amazing paragraph designed for all the online viewers; they will take advantage from it I am sure.

Also visit my webpage;  The Gospel According to Josh: A 28-Year Gentile Bar Mitzvah pdf - http://lorinerichardo.soup.io
8/23/2014 4:07:39 AM #
I am really enjoying the theme/design of your blog. Do you ever run into any internet browser compatibility issues? A small number of my blog readers have complained about my site not operating correctly in Explorer but looks great in Firefox. Do you have any suggestions to help fix this issue?

Also visit my webpage:  Traité 70-71 - http://wellingtonjoya.soup.io
8/23/2014 4:13:55 AM #
Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

Review my homepage  book download - geeklog.networkcities.net/users.php
8/23/2014 4:20:47 AM #
Hi there mates, how is everything, and what you would like to say about this article, in my view its genuinely remarkable designed for me.

Also visit my webpage; Mon imagier du Père Castor pdf [ Shari - http://haskellkeltonm.soup.io ]
8/23/2014 6:03:54 AM #
I love your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz answer back as I'm looking to construct my own blog and would like to find out where u got this from. thank you

Feel free to surf to my homepage ::  Kumarajiva: The Transcreator of Buddhist Chinese Diction pdf - http://dwendellkrystel.soup.io
8/23/2014 8:46:03 AM #
Excellent post. I was checking continuously this blog and I'm impressed! Very helpful information specifically the last part Smile I care for such information much. I was looking for this certain info for a very long time. Thank you and best of luck.

Feel free to surf to my blog;  lose Weight Fast - http://Ns.lihshan.com.tw/images/info.php?a%5B%5D=%3Ca+href%3Dhttp%3A%2F%2FVamos.cf%2Fyacon_syrup_reviews_for_weight_loss_44365%3ELose+Weight+Fast+Pills%3C%2Fa%3E
8/23/2014 11:31:57 AM #
Hi! This is my first comment here so I just wanted to give a quick shout out and tell you I really enjoy reading through your posts. Can you recommend any other blogs/websites/forums that deal with the same subjects? Appreciate it!

Also visit my blog post ::  african mango reviews - www.zahradargahi.com/.../
8/23/2014 1:03:52 PM #

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

<<  August 2014  >>
MoTuWeThFrSaSu
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

Visualizar posts em um Calendário
Sigua @fredemidio

MCP Asp.NET