MVC'de Ajax ile ViewUserControl'ü render edip dinamik olarak sayfa içine yerleştirmek nasıl yapılır?

April 29, 2009 at 1:48 PMoozturk

Merhaba,

Web Forms kullanırken ajax ile UserControl sürekli kullanıyorduk peki ya MVC'de nasıl yapılıyor? MVC ile geliştirilen projelerde ViewUserControl ve ViewPage dosyalarına karşılık gelen nesneler olmadığı ya da tipleri olmadığı için new komutuyla çağırmak mümkün değil. Ayrıca ViewData ve ViewData.Model kullanılmak istenilebilir. Bu sebeplerle farklı bir yol izlemek gerekiyor.

1. Öncelikle bu iş için MVCContrib kütüpanesi gerekiyor. Bu kütüphanede MVC  için birçok yeni kolaylık var. İndirmek için www.codeplex.com/MVCContrib adresini ziyaret edin. İndirdikten sonra projenize referans olarak MvcContrib.dll dosyasını ekleyin.

2. Aşağıda sunduğum kodu projenizin içinde istediğiniz bir yere koyun

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Security.Principal;
using MvcContrib.UI;

public static string RenderPartialToString( string userControl, ViewDataDictionary viewData, TempDataDictionary tempdata, ControllerContext controllerContext )
        {
            HtmlHelper h = new HtmlHelper( new ViewContext( controllerContext, new WebFormView( "message" ), viewData, tempdata ), new ViewPage() );
            var blockRenderer = new BlockRenderer( controllerContext.HttpContext );

            string s = blockRenderer.Capture(
                () => RenderPartialExtensions.RenderPartial( h, userControl, viewData )
            );

            return s;
        }

 

3. Bir Controller içine aşağıdaki gibi bir action'ı yazın

        public ContentResult GetEditView()
        {

            //Vıewdata içine ya da model'e birşey eklemek ya da değiştirmek istiyorsanız bunu burada yapın daha sonra aşağıdaki adımlara devam edin.
            string s= MvcStuff.RenderPartialToString( "/Views/deneme/EditView.ascx", ViewData, TempData, this.ControllerContext );
            return new ContentResult()
            {
                Content = s
            };
        }

4. Bu action'ı istediğiniz sayfa ya da ViewUserControl içinden Ajax.ActionLink ile ekleyin.

<%=        Ajax.ActionLink( "buraya basın", "GetEditView", new
          {
              Controller = "deneme"
          }, new AjaxOptions
          {
              UpdateTargetId = "mesedit"
          } )
 %><div id="mesedit">

</div>

5. Masterpage kullanıyorsanız oraya kullanmıyorsanız sayfa içine gerekli javascript kütüphanelerini ekleyin

    <script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

Bu kadar basit. Şu anda eğer aynı mantık ile yazdıysanız mesedit diye adlandırdığım div içinde usercontrol'ünüz gösterilecektir ve orada çalışacaktır. Elbette %100 Ajax. :-)

Bu arada eğer usercontrol bulunamadı diye bir hata alıyorsanız bir viewengine yazmadınız demektir. Bunun için de viewengine örneği için yazdığım yazıyı okumanızı tavsiye ederim.

Bu kütüphaneler ve jQuery sayesinde isterseniz fade gibi animasyonlar ekleyebilir, görünümü daha da güçlendirebilirsiniz.

İyi günler!

Posted in: Ajax | MVC

Tags: , , , ,

Comments (61) -

My friend referred me to your blog, so I thought I’d come have a read.  Very interesting material, will be back for more!

Reply

I really enjoyed reading your posts. They are all well written and informative. Congratulations on you achievement.

Reply

I am brand-new to blogging and actually enjoyed your website. I am going to bookmark your blog and keep checking you out. Thanks for sharing your web site.

Reply

this is sooo hard i would rather just get somebody to do this for me
www.cgwhat.com

Reply

Hi. I just noticed that your site looks like it has a few code problems at the very top of your website's page. Is it an older version of BE?  I'm not sure if everybody is getting this same bugginess when browsing your site? I am employing a totally different browser than most people, referred to as lynx, so that is what might be causing my problem? I just wanted to make sure you know. Thank you for posting some great postings and I'll try to return back with a completely different browser to check things out!

Reply

I was unaware of it till i read your post.Thanks for increasing my knowledge.

Reply

Another method for you is to stay in a house that is free from other smokers. Having to live with other smokers is such a challenge because you will be constantly tempted by the smell and by the cigarettes lying around that you can easily get.

Reply

Substantially, the post is in reality the greatest on this deserving topic. I concur with your conclusions and also will eagerly look forward to your future updates. Saying thanks can not simply be adequate, for the exceptional clarity in your writing. I will certainly right away grab your rss feed to stay abreast of any updates. Pleasant work and much success in your business dealings!

Reply

I was very pleased to find this site.I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.

Reply

Easily, the article is really the greatest on this laudable topic. I harmonise with your conclusions and will eagerly look forward to your next updates. Saying thanks will not just be enough, for the wonderful lucidity in your writing. I will immediately grab your rss feed to stay privy of any updates. Pleasant work and much success in your business dealings!

Reply

How ya doin, i I found your blog on yahoo and browse most of your other posts. I just added you to my Google News Reader. Keep up the awesome work. Looking forward to reading more from you in the future. You know, I have to tell you, I really enjoy this website and the insight from everyone who participates. I find it to be refreshing and very informative. I wish there were more blogs like it. Anyway, I felt it was about time I posted, I?ve spent most of my time here just lurking and reading, but today for some reason I just felt compelled to say this.

Reply

I enjoy reading blogs and finding out what the world is talking about. I enjoyed reading your blog and I thought it was very informative.

Reply

Very interesting blog. Alot of blogs that I see these days don't really provide anything interesting, but I am definately interested in this one. Just thought that I would pass that message on.

Reply

I just found this amazing blog article and I must say to you thank you very much for giving this article to us.

Reply

As new health care legislation hangs within the balance, thousands of Americans carry on to go without health insurance. Worse yet, as firms continue to reduce jobs, folks lose health care insurance benefits too as the income necessary to invest in an individual policy.I'm fascinated to see how all of this kind of results turning out. Hopefully, us normal people aren't harm more than this particular.

Reply

I am really not too familiar with this topic but I do like to visit blogs for layout ideas and interesting topics. You really expanded upon a subject that I usually don't care much about and made it very interesting. This is a nice blog that I will take note of. I already bookmarked it for future reference. Thx

Reply

Just wanted to say thanks for this.

Reply

Very finicky, I would convey this bleep to my comrade.

Reply

Thanks for the post, it was really helpful. I am looking forward to following your blog. Have a great day.

Reply

jobshpgcueyedhplrnn, http://honorar.si, zJpmkZBK.

Reply

Great site design!!!! Whattemplate did you use?

Reply

Greetings, I'm a college English major and I'm learning a lot about writing by reading blogs. I really like your style of writing. It's very easy to understand but with excellent details. Your choice of words makes it enjoyable to read and absorb. That's a huge portion of writing. Your followers have to be able to understand what you're saying and the article has to be engaging. You need to challenge your readers, so they will come back again. You do a good job with all of these aspects. Thank you!

Reply

Well, the article is really the freshest on this precious topic. I harmonise with your conclusions and will eagerly look forward to your upcoming updates. Just saying thanks will not just be sufficient, for the tremendous clarity in your writing. I will directly grab your rss feed to stay informed of any updates. Genuine work and much success in your business enterprize!

Reply

Oh.. that was interesting that my comment isnt shown. However I wanted to say that it's nice to see that someone else also told this as I had trouble reading the similar info elsewhere. Also, interesting article. Most readers don't think that all blogs must have comments section. On the other hand I believe that reader comments specify a blog. In short thanks for permitting us discussing on this well designed webpage. Best regards.

Reply

Please post some more of this =)

Reply

Its a pity you dont have a donate button, i would donate some =)

Reply

qxycknlwhaubwuhagpfd, http://honorar.si zaposlitev, rVHSGlL. ympldcuvirdvaxpyrafn, http://spaceheaterbuy.com space heater, PPTPbaC.

Reply

ktforalqnlywlim, <a href="http://stearnsandfoster.org">stearns and foster</a>, RsnWowFSEUOoSyHZpTRv.

Reply

smbbgkujxqxvbda, <a href="http://spaceheaterbuy.com">space heater</a>, CHMJkHTuYhSYEdKolbBZ.

Reply

The site looks kinda bad on my phone =(

Reply

edpjpdsfrbiqjso, <a href="http://honorar.si">zaposlitev</a>;, hUHhluUaVMmhKbMqhBrl.

Reply

A lot of good tutorials here, thanks.

Reply

grihmwiaavcuice, <a href="http://stearnsandfoster.org">stearns and foster</a>, rkyUYwfttmUOtmzixLez.

Reply

hwdrlqeepazzvddfwhoy, http://spaceheaterbuy.com space heater , ybHyNpgthzpaUIVLJA. ttghqalsifddnkiikyjk, http://crabtreeandevelyn.org crabtree and evelyn , xUKauJXlnYYFbDItbX.

Reply

Great site design!!!! Whattemplate did you use?

Reply

Tremendous blog. I'll have to remember to check back again.

Reply

Well, this is my first visit to your blog! We are a group of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a marvellous job! better article on the same subject at allergy-and-immunology.findhealthinfo.net/.../allergy-and-immunology.aspx

Reply

Usually I do not post on posts, but I would like to say that this site really forced me to do it! Thanks, very good post.

Reply

You got numerous positive points there. I made a search on the issue and found nearly all peoples will agree with your blog.

Reply

I am impressed, I have to say. Very seldom do I encounter a blog that's both educational and entertaining, and let me tell you, you have hit the nail on the head. Your blog is important; the issue is something that not a lot of people are talking intelligently about. I'm really happy that I stumbled across this in my search for something relating to it.

Reply

Hudrends of people will agree with your opinion whoever many other's will disagree,but I appreciate your work here.

Reply

Hey check out my blog too. I hope i have some fun stuff too

Reply

I admire the valuable information you offer in your articles. I'm very excited and longing for your next article. Hopefully I will get it this week. Really value this post especially. It's hard to separate the very good from the bad these days, but I believe you've pushed the right key! Is it possible to write a guest articles here? I would like to write a one or two articles here.

Reply

eypndcykphymrxoxnq, http://americanoutfitters.org , GwadUEKvWvuTIMZGtBnu. abyekhaagbfwenxjmt, http://kathyvanzeeland.org , UvlpdwkWqoVJwTLOuzGf.

Reply

Well with your permission allow me to grab your rss feed to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.

Reply

Thanks for posting this. i really enjoyed reading this.

Reply

I adore this blog site layout ! How was it made? It is so good.

Reply

Can you message me with some tips about how you made your website look this awesome, I'd be appreciative!

Reply

Have you thought about adding some differing opinions to the article? I think it might enhance viewers' understanding.

Reply

I'm getting a browser error, is anyone else?

Reply

I'm getting a browser error, is anyone else?

Reply

Excellence is a better teacher than mediocrity. The lessons of the ordinary are everywhere. Truly profound and original insights are to be found only in studying the exemplary.   -   Warren Bennis

Reply

Hello, I just ran across your blog via aol. and I'm really delighted I found your website. Thank You.

Reply

Cyberspace. A consensual hallucination experienced daily by billions of legitimate operators, in every nation, by children being taught mathematical concepts.

Reply

You...are...my...hero!!!  I cant believe something like this exists on the internet!  Its so true, so honest, and more than that you dont sound like an idiot!  Finally, someone who knows how to talk about a subject without sounding like a kid who didnt get that bike he wanted for Christmas.

Reply

Those who misrepresent the normal experiences of life, who decry being controversial, who shun risk, are the enemies of the American way of life, whatever the piety of their vocal professions and the patriotic flavor of their platitudes.   -   Henry M. Wriston

Reply

Hey, thanks for the article.Really thank you! Will read on...

Reply

Amazing article, lots of useful knowledge.

Reply

The Simpsons uses the regular setup of the situational comedy, or sitcom, as its premise. The series centers over a loved ones and their existence in the standard American town

Reply

Wonderful i am very glad for the information. A Fantastic page of knowledge.

Reply

Hahaha, no thanks.

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading