2014-02-03 3 views
0

У меня есть страница с индексом, содержащая элементы меню башни. При нажатии любого элемента меню я хотел бы загрузить частичный вид.Как динамически загружать частичные представления MVC5

Я использую для работы с веб-пользователями, но это несколько отличается.

В приведенном ниже коде Индекс ActionResult содержит башню пунктов меню.

Когда индексный указатель загружен, он выглядит как снимок снизу.

Index partial view

public class EnterpriseManagerController : AlumCloudMvcControllerBase 
    { 
     public class PhotoViewModel 
     { 
      public int Width { get; set; } 
      public int Height { get; set; } 
      public short MaxPhotoBytes { get; set; } 
      public string GenericPhoto { get; set; } 
      public bool IsLogo { get; set; } 
     } 

     public ActionResult Index() 
     { 
      return View(); 
     } 

     public PartialViewResult Avatar() 
     { 

      var x = new PhotoViewModel { Width = _avatarwidth, Height = _avatarheight, MaxPhotoBytes = _maxavatarbytes, GenericPhoto = _genericLogo }; 

      return PartialView(x); 
     } 
} 

Когда-либо пункт меню Аватар щелкают Я хотел бы загрузить _AvatarPartial на правой стороне башни пунктов меню. Когда вызывается ProductManagerController Avatar PartialViewResult, я хотел бы передать PhotoViewModel в PartialView (x).

Код для моего Index.cshtml выглядит следующим образом:

<div id="controlPanWrap"> 
     @Html.Partial("_VerticalMenuPartial") 

    //I NEED TO LOAD THE PARTIAL VIEWS RIGHT HERE 
    </div> 

Это то, что Аватар мой частичный вид выглядит следующим образом:

_AvatarPartial.cshtml 

Как я загружаю частичный вид Аватар чтобы содержание _AvatarPartial.cshtml соответствовало праву в процентах от

<div id="controlPanWrap"> 
     @Html.Partial("_VerticalMenuPartial") 

    _AvatarPartial.cshtml 
    </div> 

И когда какой-либо другой пункт меню щелкнул, то что _SomeOtherMenuItemPartial.cshtml вписывается в это пространство и удаляется _AvatarPartial.cshtml?

Если это можно сделать с помощью JavaScript без перезагрузки, вся страница будет замечательной.

+2

увидеть мой ответ здесь http://stackoverflow.com/questions/19643864/how-do-i-render-a-partial-form-element-using -ajax/19643974 # 19643974 –

+0

Вы можете попробовать использовать ajax для вызова метода в контроллере, который возвращает PartialView. Затем вы можете отобразить содержимое этого частичного представления в своем div div ... В качестве альтернативы вы можете увидеть ответ от парня выше меня :) –

+0

Единственное, что меня удерживает, это тот факт, что каждый из них имеет свои собственные скрипты. –

ответ

0

UiHelper.getHTML - это всего лишь оболочка объекта XMLHttpRequest.

setTimeout(function() { 

    var prevLi = document.getElementById('liAvatar'); 
    var liOnclick = function() { 
     if (this === prevLi) { return; }; 
     prevLi.removeClass('li-selected'); 
     prevLi = this.addClass('li-selected'); 


     uiHelper.getHTML({ 
      url: '/enterprisemanager/' + this.innerHTML, isAsync: true, cache: true, successCallback: function() { 

       var scripts = this.substring(this.indexOf('<script') - 7, this.lastIndexOf('<\/script>') + 9); 
       var styles = this.substring(this.indexOf('<style'), this.lastIndexOf('<\/style>') + 8); 

       var that = this.replace(scripts, ''); 
       that = that.replace(styles, ''); 


       var newScript = document.createElement('script'); 
       newScript.setText(scripts.replace('<script type="text/javascript">', '').replace('<\/script>', '')).setAttr('id', 'script_' + prevLi.innerHTML); 
       document.head.appendChild(newScript); 

       var newStyle = document.createElement('style'); 
       newStyle.setText(styles.replace('<style type="text/css">','').replace('<\/style>','')).setAttr('id', 'style_' + prevLi.innerHTML); 
       document.head.appendChild(newStyle); 

       document.getElementById('controlPanOpt').innerHTML = that; 
      } 
     }); 

    }; 
    document.body.selectorAll('.controlPanOpts li', function() { 

     for (var i = 0; i < this.length; i++) { 
      this[i].onclick = liOnclick; 
     }; 

    }); 
}, 1500); 

--My прототипы

HTMLStyleElement.prototype.setText = function (txt) { 
    /// <summary>Sets the textContent of this HTMLStyleElement to the txt param</summary> 
    /// <returns type="this" /> 
    if ('textContent' in this) { this.textContent = txt || ''; } else { this.innerText = txt || ''; }; 
    return this; 
}; 
HTMLScriptElement.prototype.setText = function (txt) { 
    /// <summary>Sets the textContent of this HTMLScriptElement to the txt param</summary> 
    /// <returns type="this" /> 
    if ('textContent' in this) { this.textContent = txt || ''; } else { this.innerText = txt || ''; }; 
    return this; 
}; 
HTMLElement.prototype.setAttr = function (name, val) { 
    /// <summary>Adds a new name and value attribute that are the name, val params</summary> 
    /// <param name="name" type="String">Name of attribute to create onto this HTMLElement</param> 
    /// <param name="val" type="String">Value to set the new name attribute being added onto this HTMLElement</param> 
    /// <returns type="this" /> 
    this.setAttribute(name, val); return this; 
}; 
Смежные вопросы