asp.net MVC - сложный пример?

Походит на задание для extra .

A.objects.extra(
    select={
        'b_count': 'SELECT COUNT(*) FROM yourapp_b WHERE yourapp_b.a_id = yourapp_a.id',
    },
    where=['b_count < 2']
)

, Если количество B - что-то, Вы часто нуждаетесь как фильтрация или упорядочивание критерия, или должны быть отображены на представлениях списка, Вы могли рассмотреть денормализацию путем добавления b_count поля к Вашему модель и использования сигналов обновить его, когда B добавлен или удален:

from django.db import connection, transaction
from django.db.models.signals import post_delete, post_save

def update_b_count(instance, **kwargs):
    """
    Updates the B count for the A related to the given B.
    """
    if not kwargs.get('created', True) or kwargs.get('raw', False):
        return
    cursor = connection.cursor()
    cursor.execute(
        'UPDATE yourapp_a SET b_count = ('
            'SELECT COUNT(*) FROM yourapp_b '
            'WHERE yourapp_b.a_id = yourapp_a.id'
        ') '
        'WHERE id = %s', [instance.a_id])
    transaction.commit_unless_managed()

post_save.connect(update_b_count, sender=B)
post_delete.connect(update_b_count, sender=B)

Другое решение состояло бы в том, чтобы управлять флагом состояния на объект, когда Вы добавляете или удаляете связанный B.

B.objects.create(a=some_a)
if some_a.hidden and some_a.b_set.count() > 1:
    A.objects.filter(id=some_a.id).update(hidden=False)

...

some_a = b.a
some_b.delete()
if not some_a.hidden and some_a.b_set.count() < 2:
    A.objects.filter(id=some_a.id).update(hidden=True)

9
задан Paul Suart 1 October 2009 в 03:16
поделиться

7 ответов

Взгляните на CodeCampServer .

Изменить: Что касается вашего запроса о моделях представления, это не идеальный ответ на него, но подумал Я бы обратил внимание на AutoMapper (используется CodeCampServer), который может помочь с автоматическим отображением данных между моделями и моделями представления, что позволяет сэкономить время в реальном времени. Также стоит рассмотреть концепцию построителей ввода (некоторые из них доступны в MVCContrib , а также некоторые в ASP.NET MVC 2 ), которые также уменьшат объем данных, которые вы должны передать в представление, инкапсулируя общие функции по всем направлениям.

Здесь есть хорошее видео о предложении ASP.NET MVC 2: http: //channel9.msdn.

6
ответ дан 3 November 2019 в 01:02
поделиться

Вы можете взглянуть на good.codeplex.com

В нем есть многое из того, что вы ищете, но есть над чем поработать! Однако после того, как вы посмотрите, я буду рад задать вопросы по этому поводу здесь или на codeplex.

Это то, на чем сейчас работает mygoodpoints.org .

2
ответ дан 3 November 2019 в 01:02
поделиться

Here ya go:

<% Html.RenderAction<LayoutController>(c => c.SearchBox()); %>
<% Html.RenderAction<LayoutController>(c => c.NavBox(Model)); %>

Put these in your masterpages, or on specific views for sidebar widgets, and abstract their logic away from your controller/viewmodel you are working on. They can even read the current RouteData (url/action) and ControllerContext (parameters/models), cause you are dealing with ambient values in these objects - and executing a full ActionMethod request!

I blogged about this little known secret here. I also blogged about where this is located, which is the ASP.NET 1.0 MVC Futures assembly that is a seperate add-on from Microsoft.

Steve Sanderson actually gives gives examples of complex logic and application building in a book I have called Pro ASP.NET MVC (shameless plug, I know, but it's what you are looking for in your question), where he actually uses the RenderAction! I made the blog post, before I even read the book so I am glad we are on the same page.

Actually, there are dozens of extensions and functionality that was developed by the ASP.NET MVC team that was left out of the ASP.NET MVC 1.0 project - most of which makes complex projects much more managable. This is why more complex examples (list above in most people's answers) have to use some type of custom ViewEngine, or some big hoop jumping with base controllers and custom controllers. I've looked at almost all of the open source versions listed above.

But what it comes down to is not looking at a complex example, but instead knowing the ways to implement the complex logic that you desire - such as your Navigation bar when all you have is a ViewModel in a single controller to deal with. It gets tiring very quickly having to bind your navbar to each and every ViewModel.

So, an example of these is the Html.RenderAction() extension (as I started off with) that allows you to move that more complex/abstracted logic off of the viewmodel/controller (where it is NOT even your concern), and place it in its own controller action where it belongs.

This littler baby has saved MVC for me, especally on large scale enterprise projects I am currently working on.

You can pass your viewmodel into the RenderAction, or just render anything like a Footer or Header area - and let the logic be contained within those actions where you can just fire and forget (write the RenderAction, and forget about any concern of what it does for a header or footer).

3
ответ дан 3 November 2019 в 01:02
поделиться

Насколько мне известно, Контроллер напрямую возвращает представление и может передавать данные в представление, используя либо ViewData, либо контекст.

Первый - это просто свободный мешок с различными битами. данных, тогда как последний является особым типом.

ViewModel будет передан в View как контекст (и разметка View будет строго типизирована для того типа ViewModel, который он ожидает).

] Это мои 2 цента :) Надеюсь, это помогло - извините, я не смог добавить загружаемые примеры.

0
ответ дан 3 November 2019 в 01:02
поделиться

Должна ли моя ViewModel иметь свойства, чтобы охватить каждый аспект "страницы" я стремлюсь рендерить как вывод?

Да. Есть еще один вариант с RenderAction, но помимо этого ViewModel в целом часто бывает большим, и вам нужно найти хороший способ заполнить его. Я признаю, что сначала это звучит как проблемное место.

0
ответ дан 3 November 2019 в 01:02
поделиться

AtomSite - это движок блога, написанный с использованием ASP.NET MVC

0
ответ дан 3 November 2019 в 01:02
поделиться

Для автоматической передачи данных во все представления вы можете создать свой собственный класс контроллера и использовать его:

Пример

    public class MyController : Controller

{
    private User _CurrentUser;

    public User CurrentUser
    {
        get
        {
            if (_CurrentUser == null)
                _CurrentUser = (User)Session["CurrentUser"];
            return _CurrentUser;
        }
        set
        {
            _CurrentUser = value;
            Session["CurrentUser"] = _CurrentUser;
        }
    }

    /// <summary>
    /// Use this override to pass data to all views automatically
    /// </summary>
    /// <param name="context"></param>
    protected override void OnActionExecuted(ActionExecutedContext context) 
    {
        base.OnActionExecuted(context);

        if (context.Result is ViewResult) 
        {
            ViewData["CurrentUser"] = CurrentUser;
        }
    }
    }
0
ответ дан 3 November 2019 в 01:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: