MVC, ascx, and Javascript best practices - how to create self-contained controls? NerdDinner does it wrong

The question is how to create controls / partial views / edittemplates (ascx files) in ASP.Net MVC2 so that they are "self-contained". Self-preservation means that if any Javascript code is to be applied to a control that is not included in the page (aspx), but the control itself. Case study: NerdDinner DateTime.ascx. The file contains JS code that makes the text field a good DateTime picker.

My problems: The containing page contains jQuery.js, timepicker.js, jQueryUI css and datepicker css. (In the case of NerdDinner, they are all on the main page). Therefore, whenever I would like to use a fancy DateTimePicker for DateTime types, the containing page should know these dependencies and should add all js and css files. I think I missed a solution here that replaces ClientScript.RegisterClientScriptBlock.

Another problem with the same NerdDinner example: In DateTime.ascx, it says $ ('# Dinner_EventDate'), which is a dependency on both the type of the container and the name of the property. This is not a general solution for a ShareTemplate with a DateTime delimiter.

Any suggestions?

+3
source share
2 answers

You need to link these files from the page. Otherwise, you will hack your way against how these elements are included in html, and where your control is included in the page.

What we do, we attach all these separate js / css files to a single file with additional code (once). This way, you only link to one file from your main page . So far, you have nothing particularly difficult about this, which is very reasonable.

For id problem, change jquery to search by css class .


original answer: ignore below, I thought it was not yet in separate files.

Move it to the .js file and change it with id to use the class.

/.js-, , , , .js . js . , , .

0

, , MVC. - , (, script). ASCX -. , CSS JS- . , DLL. , . , . , , . , : http://msdn.microsoft.com/en-us/library/aa719734%28v=vs.71%29.aspx

ASCX javascript CSS, script (, , , Javascript, CSS). :

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      dim myScript as new StringBuilder
      myScript.Append("function helloWorld(){" & vbcrlf)
      myScript.Append("alert('Hi')" & vbcrlf)
      myScript.Append("}" & vbcrlf)

      ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType(),"MyScript",myScript.toString, false)
  End Sub

javascript . , javascript, . , , CSS. , .

0

Source: https://habr.com/ru/post/1764710/


All Articles