Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 22

0
votes
answers
44 views
+10

如何響應文件流和json對象作爲Web API的單一響應

-1

Web API, 我當前的Web API正在響應具有2個屬性的JSON對象,如下所示。 我想:1,字段名稱:somename如何響應文件流和json對象作爲Web API的單一響應

現在,需要在響應中包含一個FILE(.CERT)以及現有的JSON屬性。

如何做到這一點?

[授權]

[Route("getfileAndProperties")] 
public HttpResponseMessage GetTestFile() 
{ 
    HttpResponseMessage result = null; 
    var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.cer"); 

    var p = new Person() {Id=1,userField="name"}; 
//need to include this Person object into response along with file. 
    if (!File.Exists(localFilePath)) 
    { 
     result = Request.CreateResponse(HttpStatusCode.Gone); 
    } 
    else 
    { 
     // Serve the file to the client 
     result = Request.CreateResponse(HttpStatusCode.OK); 
     result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read)); 
     result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
     result.Content.Headers.ContentDisposition.FileName = "SampleImg";     
    } 

    return result; 
} 
+0

你能分享一下你的代碼嗎? –

+0

@Div新增評論。 – user3711357

沙发
0
0

實測值使用文件的Base64String轉化率和溶液包括入JSON響應。

謝謝

0
votes
answers
44 views
+10

如何將動態生成的網頁顯示到新選項卡?

0

我在後面的代碼中動態生成了一個網頁。如何可以加載並在這裏用戶桌面(C#,asp.net)上顯示 是我的代碼:?如何將動態生成的網頁顯示到新選項卡?

 StringBuilder strHtm = new StringBuilder(); 


     strHtm.Append("<html>"); 
     strHtm.Append(Environment.NewLine); 

     strHtm.Append("<head>"); 
     strHtm.Append(Environment.NewLine); 
     strHtm.Append("<meta http-equiv=Content-Type content="text/html; charset=utf-8">"); 
     strHtm.Append(Environment.NewLine); 

     strHtm.Append("</head>"); 
     strHtm.Append(Environment.NewLine); 

     strHtm.Append("<body>"); 
     strHtm.Append(Environment.NewLine); 

     //some code here reading from datatable 

     strHtm.Append("</body>"); 
     strHtm.Append(Environment.NewLine); 

     strHtm.Append("</html>"); 
     strHtm.Append(Environment.NewLine); 

現在,我怎麼加載它在瀏覽器新標籤或窗口?

+0

您不能**推送**頁面。你需要一個訪客點擊的鏈接('load')來在新窗口/標籤中加載你的頁面(取決於瀏覽器設置)。 –

+0

你的意思是我應該保存網頁然後創建一個鏈接? – jaleel

+0

當用戶單擊鏈接時,您應該提供該頁面。 –

沙发
0
1
  1. 添加另一個ASP頁面
  2. 添加一個佔位符,新創建的ASP頁面
  3. 刪除HTML,頭部,身體標記
  4. 最後加入這行代碼在Page_Load中

    PlaceHolder1.Controls.Add(new LiteralControl(strHtm.ToString().Trim()))  
    
0
votes
answers
32 views
+10

如何使控制器中的動作接收來自未知數量輸入的更多數據

-2

如何使控制器中的動作接收來自未知數量輸入的更多數據?如何使控制器中的動作接收來自未知數量輸入的更多數據

我想要點擊更多的選項輸入更多的信息,這意味着HTML頁面上的DOM樹越來越多,我不知道如何使操作接收來自HTML頁面上未知數量輸入的數據。

這是我的html代碼

<div class="form-group"> 
<label class="col-md-2 lableAlign">Course Name</label> 
<div class="col-md-6"> 
<input class="col-md-6" type="text" name="courseTitle" id="courseTitle" value="Thamar" maxlength="20"> 
@Html.ValidationMessageFor(model => model.courseTitle, "", new { @class = "text-danger" }) 
</div> 
</div> 

<div class="form-group"> 
<label class="col-md-2 lableAlign">Certificate</label> 
<div class="col-md-6"> 
<input class="col-md-6 r" type="file" name="courseCertificate" id="courseCertificate" val`enter code here`ue=""> 
@Html.ValidationMessageFor(model => model.courseCertificate, "", new { @class = "text-danger" }) 
</div> 
</div> 

<div class="form-group more" id="corceMore"> 
<label class="col-md-3 more" onclick="corceAdd()">More +</label> 

</div> 

這是我的javascript代碼

function corceAdd() { 
++corcecount; 
if (corcecount < 20) { 
     $("<div class="divStyle"><div class="form-group"><label class="col-md-2 lableAlign">??? ??????</label><div class="col-md-6"><input class="col-md-6" type="text" name="corceTitle" + corcecount + "" id="corceTitle" + corcecount + "" value=""></div></div><div class="form-group"><label class="col-md-2 lableAlign">???????</label><div class="col-md-6"><input class="col-md-6 r" type="file" name="corceCertificate" + corcecount + "" id="corceCertificate" + corcecount + "" value=""></div></div>").insertBefore("#corceMore"); 

} 
} 

當點擊更多選項的新元素它的標識和名稱由一個增加,現在我的問題是當我點擊提交我想要發送所有元素值到控制器中的後操作。

沙发
0
0

有很多關於這個問題的文章和主題:

http://techiesweb.net/2012/09/17/asp-net-mvc3-dynamically-added-form-fields-model-binding.html

ASP.NET MVC Dynamic Forms

我將展示的重點。如何將動態輸入綁定到動作模型。

您需要有一個集合作爲模型。

public class SampleViewModel 
{ 
    public IEnumerable<SampleItemViewModel> Items {get;set;} 
} 

public class SampleItemViewModel 
{ 
    public string Id {get;set;} 
} 

然後在Razor視圖,你應該創建一個輸入這樣的:

<input id='Items__0__Id' type='hidden' name='Items[0].Id' /> 
<input id='Items__1__Id' type='hidden' name='Items[1].Id' /> 

所以,你應該綁定的名稱輸入到索引集合的性質。然後在你的行動:

public ActionResult Post(SampleViewModel model) 
{ 
    var items = model.Items; // Here you should have your collection 
} 
+0

謝謝,但你的答案並不能解決我的問題,你可以看到更多的解釋與上面的代碼。 –

+0

您能否請您展示您的控制器操作和模型? – Iaroslav

76
votes
answers
21 views
+10

Font files are not loading with ASP.NET Bundles

In my ASP.NET MVC application, I'm using Bundles to compress css and js files. The problem is - the fonts are not loading after i enable the optimization mode.

BundleTable.EnableOptimizations = true;

Here is the C# code

public static void RegisterBundles(BundleCollection bundles) {
    RegisterStyles(bundles);
    BundleTable.EnableOptimizations = true;
}

private static void RegisterStyles(BundleCollection bundles) {
bundles.Add(new StyleBundle("~/BundleStyles/css").Include(
    "~/Content/Styles/bootstrap/bootstrap.css",
    "~/Content/Styles/reset.css",
    "~/Content/Styles/gridpack/gridpack.css",

    "~/Content/Styles/fontFaces.css",
    "~/Content/Styles/icons.css",

    "~/Content/Styles/inputs.css",
    "~/Content/Styles/common.css",
    "~/Content/Styles/header.css",
    "~/Content/Styles/footer.css",
    "~/Content/Styles/cslider/slider-animations.css",
    "~/Content/Styles/cslider/slider-base.css"));
}

And here is the css for fonts.

   @font-face {
      font-family: ProximaNova;
      src: url('../Fonts/ProximaNova/ProximaNova-Bold.otf') format('opentype');
      font-weight: bold;
      font-style: normal;
    }

Here is how CSS is beeing referenced in the page.

<link href="/BundleStyles/css?v=pANk2exqBfQj5bGLJtVBW3Nf2cXFdq5J3hj5dsVW3u01" rel="stylesheet"/>

However, when i checked with Chrome Debugger tool, the font files are not loading to the page and my page looks bad with wrong fonts.

What am I doing wrong?

up vote 39 down vote accepted favorite
沙发
+390
+50

Well, I think the problem is with your font location. I'm assuming that the bundled css virtual location /BundleStyles/css doesn't actually exist. and if your folders structure like below

Content > Font

Content > style

If this is true, then try this

change /BundleStyles/css to /Content/css

<link href="/Content/css?v=pANk2exqBfQj5bGLJtVBW3Nf2cXFdq5J3hj5dsVW3u01" rel="stylesheet"/>

and reference your font like this

src: url('Fonts/ProximaNova/ProximaNova-Bold.otf')

in this case your font will be loaded relative to the "css" file which is located inside the content folder which also contains the "fonts" folder

If what I assumed is incorrect please show us how you structured your files

當您部署到IIS時,您可能會發現這個有用,codingstill.com/2013/01/set-mime-types-for-web-fonts-in-iis - SimonGates 2013年9月25日15:25

我的答案有問題:它不能在調試模式下工作,因為字體將在樣式文件夾下面引用,所以這就是我解決它的方法:我有一個Content / css文件夾和一個Content / fonts文件夾。我將bundle虛擬路徑設置為“〜/ Content / css / styles”,這樣我就不必從字體引用中刪除“../”,因為fonts文件夾將保持在“styles”文件之上一級。也就是說,它在調試模式下保持正常工作,因為路徑深度保持不變。 - Boanerge 2015年11月11日19:26

我有相同的問題訪問字體真棒字體,其他解決方案嘗試這些鏈接處理StyleBundle虛擬路徑:鏈接1,鏈接2,鏈接3,鏈接4,希望這有助於某人。 - 2016年2月25日9:39

對我來說,沒有你的字體和其他css資源中斷的最簡單的解決方案是保持你的捆綁在同一深度。例如,如果要捆綁〜/ content / file.css,請調用bundle~ / content / file_bundle,調試和發布之間不應該有任何問題。 - aleith 2月5日13:53

+290

I think CssRewriteUrlTransform might be the way to go:

https://msdn.microsoft.com/en-us/library/system.web.optimization.cssrewriteurltransform(v=vs.110).aspx

Used like so:

.Include("~/Content/bootstrap-cosmo.min.css", new CssRewriteUrlTransform())

Worked for me.

非常感謝!!這個問題的最佳解決方案! - Pilgerstorfer Franz 18年10月17日19:47

+70

Great answer above.

An alternative - if for some reason the above didn't work for you - would be to change how the @font-face src property references the 'Fonts' folder. '../'-ing doesn't work very well for bundling so reference directly from the site root folder instead. Assumung the 'Fonts' folder is one down from the root, change this:

@font-face {
  src: url('../Fonts/ProximaNova/ProximaNova-Bold.otf') format('opentype');
}

To this:

@font-face {
  src: url('/Fonts/ProximaNova/ProximaNova-Bold.otf') format('opentype');
}

You will retrieve the same results when the site is ran in debug mode too.

如果您的應用程序部署為虛擬應用程序--Laserson於2016年3月29日2:12,它不起作用

為我工作; 謝謝! - 聯繫馬克於2016年10月9日18:27

+10

I went looking online for this today because I am running into this issue. Here's what worked for me:

  1. The /bundle/ wasn't actually an issue (I tried this first)
  2. I changed single quotes to double quotes & the fonts worked - but no idea why, so if someone knows please feel free to elaborate.
0
votes
answers
25 views
+10

我的登錄頁面被瀏覽器驗證框取代

0

我正在開發一個帶有用戶登錄的asp.net web應用程序。它在開發環境上工作得很好。我的登錄頁面被瀏覽器驗證框取代

當用戶只需要訪問成員頁面我的login.aspx文件顯示,但在發佈後,僅顯示僅成員頁面請求瀏覽器本地登錄頁面而不顯示我的login.aspx。請幫我解決這個問題:
enter image description here

+1

你可以直接粘貼內的圖像你的問題?您是否使用HTTP BASIC身份驗證? –

沙发
0
0

它,因爲你使用的是Windows身份驗證,它似乎是你的測試環境是不可能的域(機器或Active Directory)的

0
votes
answers
8 views
+10

從內容頁面調用主頁面的方法Web方法

0

我在主頁面上有一個方法(非靜態),將從內容頁面Method(靜態WebMethod)調用。 如 母版頁:從內容頁面調用主頁面的方法Web方法

public partial class User : System.Web.UI.MasterPage 
{ 
public void loadcart() 
{ 
//some code here that i will a div 
} 
} 

內容頁:

public partial class Menu : System.Web.UI.Page 
{ 
[webMethod] 
public static void Order() 
{ 
// some code here 
// call Master page method from here 
} 
} 

令()(內容頁面方法)將從jQuery的AJAX和loadcar()(母版頁功能)稱爲將在Order()函數中調用。

我需要從內容頁面調用母版頁方法。請爲我提供一些解決方案。

有什麼想法嗎?

+1

[主頁面調用方法]的可能重複(https://stackoverflow.com/questions/6332889/call-method-in-master-page) – Alexander

沙发
0
0

例如,如果您想調用loadcart,您可以執行masterpage的轉換。

  (this.Master as SiteMaster).loadcart(); 
0
votes
answers
35 views
+10

如何使網格視圖頁腳控件可見,如果網格視圖爲空

0

我有一個網格視圖控件在我的頁面中索引所有Lecture Contents。我添加了一個Text Box控件和一個Link Button。但對於沒有內容的講座,Grid View沒有出現。 已經嘗試了很多參考文獻,因此頁腳已經出現,但我無法在頁腳中使用Controls插入數據。 我的主要目標是使Controls在兩種情況下表現相同。 這是網格視圖代碼。如何使網格視圖頁腳控件可見,如果網格視圖爲空

`<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="No Contents found for this lecture." ShowFooter="true" HeaderStyle-Wrap="false" Width="70%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"> 
    <AlternatingRowStyle BackColor="White" /> 
    <Columns> 
     <asp:TemplateField HeaderText=" LectureID " SortExpression="lecc_id"> 
     <ItemTemplate> 
      <asp:Label ID="lbllecc_id" runat="server" Text='<%# Bind("lecc_id") %>'></asp:Label> 
     </ItemTemplate> 
     <FooterTemplate> 
      <asp:Label ID="lbllecc_id" runat="server" T`enter code here`ext="Create New"> 
    </asp:Label> 
     </FooterTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText=" Content " SortExpression="lecc_contents"> 
      <EditItemTemplate> 
       <asp:TextBox ID="tblecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:TextBox> 
      </EditItemTemplate> 
      <ItemTemplate> 
       <asp:Label ID="lbllecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:Label> 
      </ItemTemplate> 
      <FooterTemplate> 
       <asp:TextBox ID="txtcontent" runat="server"></asp:TextBox> 
      <asp:RequiredFieldValidator ID="rfcontent" runat="server" ErrorMessage="Content field cannot be blank." ControlToValidate="txtcontent" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>           
      <asp:LinkButton ID="createcontent" runat="server" OnClick="createcontent" CssClass="btn-sm btn-default">Insert Content</asp:LinkButton> 
     </FooterTemplate> 
     </asp:TemplateField> 
    </Columns> 
    </EmptyDataTemplate> 
    <FooterStyle BackColor="#CCCC99" /> 
    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Font-Size="17px" /> 
    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" /> 
    <RowStyle BackColor="#F7F7DE" Font-Bold="False" Font-Size="14px" /> 
    <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" /> 
    <SortedAscendingCellStyle BackColor="#FBFBF2" /> 
    <SortedAscendingHeaderStyle BackColor="#848384" /> 
    <SortedDescendingCellStyle BackColor="#EAEAD3" /> 
    <SortedDescendingHeaderStyle BackColor="#575357" /> 
</asp:GridView>` 

和網格視圖功能的代碼。

`protected void Page_Load(object sender, EventArgs e){ 
if (Session["fac_username"] != null) 
{ 
    String username = Convert.ToString(Session["fac_username"]); 
    if (!IsPostBack) 
    { 
     BindGridViewData(); 
    } 
} 
else 
{ 
    Response.Redirect("~/Account/Login.aspx"); 
} 
}protected void BindGridViewData(){ 
int lecID = Convert.ToInt32(Session["lecID"]); 
GridView1.DataSource = DataAccessLayer.getAllContents(lecID); 
GridView1.DataBind();}   protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){ 
      } 
protected void createcontent(object sender, EventArgs e){ 
int lecID = Convert.ToInt32(Session["lecID"]); 
con.Open(); 
SqlCommand command = new SqlCommand("insert into uni_lect_content(lecc_id, lecc_contents) values(@lecc_id, @lecc_contents)", con); 
command.Parameters.AddWithValue("@lecc_id", lecID); 
command.Parameters.AddWithValue("@lecc_contents", ((TextBox)GridView1.FooterRow.FindControl("txtcontent")).Text); 
command.ExecuteNonQuery(); 
con.Close(); 
lblmsg.Text = "New Course Successfully Created..!";}` 

DataAccessLayer類的getAllConents()方法在這裏。

`public class AllContents 
{ 
    public long lecc_id { get; set; } 
    public string lecc_contents { get; set; } 
} 
public class DataAccessLayer 
{ 
    public static List<AllContents> getAllContents(int lecID){ 
     List<AllContents> listAll = new List<AllContents>(); 
     string cs = ConfigurationManager.ConnectionStrings["ILMSConnectionString"].ConnectionString; 
     using (SqlConnection con = new SqlConnection(cs)) 
     { 

      SqlCommand com = new SqlCommand("select lecc_id, lecc_contents from uni_lect_content, uni_lectures, uni_offered_courses where uni_lect_content.lecc_id = uni_lectures.lec_id and uni_lectures.cours_offer_id = uni_offered_courses.cours_offer_id and lecc_id = '"+lecID+"'", con); 
      con.Open(); 
      SqlDataReader rdr = com.ExecuteReader(); 
      while (rdr.Read()) 
      { 
       AllContents obj = new AllContents(); 
       obj.lecc_id = Convert.ToInt32(rdr["lecc_id"]); 
       obj.lecc_contents = rdr["lecc_contents"].ToString(); 
       listAll.Add(obj); 

      } 
     } 
    return listAll; 
}` 

幫我脫離這種情況。 在此先感謝。

沙发
0
0

前端GRDIVIEW

<asp:GridView ID="grdview" ShowFooter="true" OnRowEditing="grdview_RowEditing" OnRowCancelingEdit="grdview_RowCancelingEdit" OnRowCommand="grdview_RowCommand" OnRowUpdating="grdview_RowUpdating" runat="server" AutoGenerateColumns="false"> 
        <Columns> 
         <asp:TemplateField HeaderText="SR No."> 
          <ItemTemplate> 
           <%#Container.DataItemIndex+1 %> 
           <asp:Label ID="lblid" runat="server" Text='<%#Eval("Id") %>'></asp:Label> 
          </ItemTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp Name"> 
          <ItemTemplate> 
           <asp:Label ID="elblempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:Label> 
          </ItemTemplate> 
          <EditItemTemplate> 
           <asp:TextBox ID="etxtempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox> 
          </EditItemTemplate> 
          <FooterTemplate> 
           <asp:TextBox ID="ftxtempname" runat="server" ></asp:TextBox> 
          </FooterTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp No"> 
          <ItemTemplate> 
           <asp:Label ID="elblempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:Label> 
          </ItemTemplate> 
          <EditItemTemplate> 
           <asp:TextBox ID="etxtempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:TextBox> 
          </EditItemTemplate> 
          <FooterTemplate> 
           <asp:TextBox ID="ftxtempno" runat="server" ></asp:TextBox> 
          </FooterTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Email"> 
          <ItemTemplate> 
           <asp:Label ID="elblempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:Label> 
          </ItemTemplate> 
          <EditItemTemplate> 
           <asp:TextBox ID="etxtempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:TextBox> 
          </EditItemTemplate> 
         <FooterTemplate> 
           <asp:TextBox ID="ftxtempemail" runat="server" ></asp:TextBox> 
          </FooterTemplate> 
         </asp:TemplateField> 
         <asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Age"> 
          <ItemTemplate> 
           <asp:Label ID="elblempage" runat="server" Text='<%#Eval("Age") %>'></asp:Label> 
          </ItemTemplate> 
          <EditItemTemplate> 
           <asp:TextBox ID="etxtempage" runat="server" Text='<%#Eval("Age") %>'></asp:TextBox> 
          </EditItemTemplate> 
          <FooterTemplate> 
           <asp:TextBox ID="ftxtempage" runat="server" ></asp:TextBox> 
           <asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" /> 
          </FooterTemplate> 
         </asp:TemplateField> 
</Columns> 
       </asp:GridView> 

後端代碼

ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); 
         grdview.DataSource = ds; 
         grdview.DataBind(); 
         int columncount = grdview.Rows[0].Cells.Count; 
         grdview.Rows[0].Cells.Clear(); 
         grdview.Rows[0].Cells.Add(new TableCell()); 
         grdview.Rows[0].Cells[0].ColumnSpan = columncount; 
         grdview.Rows[0].Cells[0].Text = "No Records Found"; 
if (e.CommandName == "AddNew") 
     { 
      TextBox ftxtempname = (TextBox)grdview.FooterRow.FindControl("ftxtempname"); 
      TextBox ftxtempno = (TextBox)grdview.FooterRow.FindControl("ftxtempno"); 
      TextBox ftxtempemail = (TextBox)grdview.FooterRow.FindControl("ftxtempemail"); 
      TextBox ftxtempage = (TextBox)grdview.FooterRow.FindControl("ftxtempage"); 
      using (con) 
      { 
       SqlCommand cmd = new SqlCommand("usp_add_upd_emptb", con); 
       cmd.CommandType = CommandType.StoredProcedure; 
       cmd.Parameters.AddWithValue("@EmpName", ftxtempname.Text); 
       cmd.Parameters.AddWithValue("@EmpNo", ftxtempno.Text); 
       cmd.Parameters.AddWithValue("@Desig", ftxtempage.Text); 
       cmd.Parameters.AddWithValue("@Email", ftxtempemail.Text); 

       con.Open(); 
       cmd.ExecuteNonQuery(); 
} 

這是一個完整的工作代碼。

+0

我已經通過這樣的例子,但對於我的特殊情況,我無法實現邏輯。 @Vipin你能否爲我解釋一下,記住我的代碼。請。 。 –

+0

@StartarJamali如果這還不能解決您的問題,請不要將其標記爲已接受。 – AsifAli72090

+0

好的。 @ Asif.Ali。 .. 我可以問你的解決方案..? 我需要它緊急。 。 –

0
votes
answers
51 views
+10

Gulp Js&BundleConfig.json Sass不編譯@Import?

2

我是新來的整個Grunt/Gulp設置,我試圖設置一個簡單的解決方案。我的JS,Html和CSS是各種各樣的工作。但是我無法讓SASS正確編譯。這是一個使用BundleConfig.json文件的.Net核心應用程序,該文件在我的gulpfile.js中正在使用。Gulp Js&BundleConfig.json Sass不編譯@Import?

我的CSS文件結束了這樣

@import"_variables.scss";@import"base.scss"; 

沒有SASS被編譯,現在我卡住了。

這裏是我的bundleconfig.json

[ 
    { 
    "outputFileName": "wwwroot/css/sass.min.css", 
    "inputFiles": [ 
     "sass/main.scss" 
    ] 
    }, 
    { 
    "outputFileName": "wwwroot/css/all.min.css", 
    "inputFiles": [ 
     "node_modules/bootstrap/dist/css/bootstrap.min.css", 
     "node_modules/bootstrap/dist/css/bootstrap-grid.min.css", 
     "wwwroot/css/sass.min.css" 
    ] 
    }, 
    { 
    "outputFileName": "wwwroot/js/all.min.js", 
    "inputFiles": [ 
     "node_modules/jquery/dist/jquery.min.js", 
     "node_modules/jquery-validation/dist/jquery.validate.min.js", 
     "node_modules/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js", 
     "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js", 
     "scripts/**/*.js" 
    ], 
    "minify": { 
     "enabled": true, 
     "renameLocals": true 
    }, 
    "sourceMap": false 
    } 
] 

這裏是我的gulpfile.js

"use strict"; 

var gulp = require("gulp"), 
    scsscompile = require("gulp-sass"), 
    concat = require("gulp-concat"), 
    cssmin = require("gulp-cssmin"), 
    htmlmin = require("gulp-htmlmin"), 
    uglify = require("gulp-uglify"), 
    merge = require("merge-stream"), 
    del = require("del"), 
    bundleconfig = require("./bundleconfig.json"); 

var regex = { 
    scss: /.scss$/, 
    css: /.css$/, 
    html: /.(html|htm)$/, 
    js: /.js$/ 
}; 

gulp.task("min", ["min:js", "min:scss", "min:css", "min:html"]); 

gulp.task("min:js", function() { 
    var tasks = getBundles(regex.js).map(function (bundle) { 
     return gulp.src(bundle.inputFiles, { base: "." }) 
      .pipe(concat(bundle.outputFileName)) 
      .pipe(uglify()) 
      .pipe(gulp.dest(".")); 
    }); 
    return merge(tasks); 
}); 

gulp.task("min:scss", function() { 
    var tasks = getBundles(regex.scss).map(function (bundle) { 
     return gulp.src(bundle.inputFiles, { base: "." }) 
      .pipe(concat(bundle.outputFileName)) 
      .pipe(scsscompile({ includePaths: ['./sass'] })) 
      .pipe(gulp.dest(".")); 
    }); 
    return merge(tasks); 
}); 

gulp.task("min:css", function() { 
    var cssTasks = getBundles(regex.css).map(function (bundle) { 
     return gulp.src(bundle.inputFiles, { base: "." }) 
      .pipe(concat(bundle.outputFileName)) 
      .pipe(cssmin()) 
      .pipe(gulp.dest(".")); 
    }); 
    return merge(cssTasks); 
}); 

gulp.task("min:html", function() { 
    var tasks = getBundles(regex.html).map(function (bundle) { 
     return gulp.src(bundle.inputFiles, { base: "." }) 
      .pipe(concat(bundle.outputFileName)) 
      .pipe(htmlmin({ collapseWhitespace: true, minifyCSS: true, minifyJS: true })) 
      .pipe(gulp.dest(".")); 
    }); 
    return merge(tasks); 
}); 

gulp.task("clean", function() { 
    var files = bundleconfig.map(function (bundle) { 
     return bundle.outputFileName; 
    }); 

    return del(files); 
}); 

gulp.task("watch", function() { 
    getBundles(regex.js).forEach(function (bundle) { 
     gulp.watch(bundle.inputFiles, ["min:js"]); 
    }); 

    getBundles(regex.scss).forEach(function (bundle) { 
     gulp.watch(bundle.inputFiles, ["min:scss"]); 
    }); 

    getBundles(regex.css).forEach(function (bundle) { 
     gulp.watch(bundle.inputFiles, ["min:css"]); 
    }); 

    getBundles(regex.html).forEach(function (bundle) { 
     gulp.watch(bundle.inputFiles, ["min:html"]); 
    }); 
}); 

function getBundles(regexPattern) { 
    return bundleconfig.filter(function (bundle) { 
     return regexPattern.test(bundle.outputFileName); 
    }); 
} 
而我試圖編譯 main.scss

我無禮文件僅僅是這一點,進口到同一個目錄中的Sass文件。

@import "_variables.scss"; 
@import "base.scss"; 

當我運行grunt任務時,我得到了這個?

預期分號或關閉大括號,發現「 - 」預期
分號或關閉大括號,發現「 - 」預期分號或
閉大括號,實測「 - 」的意外標記,發現'@import'
意外的令牌,發現 ' 「_variables.scss」' 意外令牌,發現
'@import' 意外令牌,發現 ' 「base.scss」'

任何幫助,將不勝感激。

沙发
0
0

getBundles()函數正在尋找outputFilename中的regex.scss模式。在bundleconfig.json中,輸出文件名以.css或.js擴展名結尾。

您將需要更改分鐘:SCSS任務類似如下:

gulp.task("sass", function() { 
 
    var tasks = gulp.src('./sass/main.scss') 
 
        .pipe(sass().on('error', sass.logError)) 
 
        .pipe(gulp.dest('./wwwroot/css')); 
 
    return merge(tasks); 
 
});

我所做的是 - 我已經明確表示,尋找在main.scss文件sass文件夾。你可以編寫一個glob模式來查找sass文件夾中的所有scss。如果你想嚴格遵守bundleconfig.json,那麼你需要編寫一個新的getbundles()函數來查找具有.scss擴展名的輸入文件並返回該文件。

希望這有助於

0
votes
answers
66 views
+10

爲什麼HttpClient PutAsync在成功更新後返回內部服務器錯誤

0

我有一個HttpPut API方法,用於編輯它傳遞併成功保存到數據庫中的對象。這工作正常,但是從我的MVC應用程序,我用來調用我的API Put方法的httpClient.PutAsync返回內部服務器錯誤,即使API Put方法沒有。爲什麼HttpClient PutAsync在成功更新後返回內部服務器錯誤

我不知道什麼錯誤,API方法工作正常,但不知何故MVC的HttpClient仍然得到一個內部服務器錯誤。

API put方法

[HttpPut] 
    public IActionResult Put([FromBody] School school) 
    { 
     try 
     { 
      var schoolExists = _schoolRepository.SchoolExists(school.Id); 

      if (!schoolExists) return NotFound(); 

      if (!ModelState.IsValid) return BadRequest(); 

      var schoolData = Mapper.Map<School, Data.School>(school); 

      var updatedClass = _schoolRepository.UpdateSchool(schoolData); 

      if (!updatedClass) return Json(GetHttpResponseMessage(HttpStatusCode.InternalServerError)); 

      var route = CreatedAtRoute("GetSchool", school); 

      return route; 
     } 
     catch (Exception e) 
     { 
      return LogException(e); 
     } 
    } 

上述方法,工作正常,我的改變被保存到數據庫中,CreatedAtRouteResult對象從API方法返回。上述

MVC的HttpClient

public async Task<T> PutObject(string path, T content, string accessToken) 
    { 
     using (var httpClient = new HttpClient()) 
     { 
      try 
      { 
       SetBaseUri(httpClient, accessToken); 

       var serialisezContent = CreateHttpContent(content); 

       var httpResponse = await httpClient.PutAsync(path, serialisezContent); 

       if (httpResponse.StatusCode == HttpStatusCode.InternalServerError) throw new Exception("Problem accessing the api"); 

       return JsonConvert.DeserializeObject<T>(GetResult(httpResponse)); 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
     } 

    } 

的方法,其中是問題是,這條線var httpResponse = await httpClient.PutAsync(path, serialisezContent);仍返回內部服務器錯誤。我的POST有相同的實現,並且工作得很好。

SETBASEURI()

private void SetBaseUri(HttpClient httpClient, string accessToken) 
    { 
     httpClient.BaseAddress = new Uri(BaseUri); 
     httpClient.DefaultRequestHeaders.Authorization = 
      _authenticationHeaderValueCreator.CreateAuthenticationHeaderValue("bearer", accessToken); 
    } 

CreateHttpContent()

public ByteArrayContent CreateHttpContent<TParam>(TParam httpObject) 
    { 
     var content = JsonConvert.SerializeObject(httpObject); 
     var buffer = System.Text.Encoding.UTF8.GetBytes(content); 
     var byteContent = new ByteArrayContent(buffer); 

     byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 

     return byteContent; 
    } 
沙发
0
0

我敢打賭,你的API Put方法確實有消息No route matches the supplied values返回HTTP 500錯誤。你可以在Fiddler中檢查它。

而問題是具有以下線:

var route = CreatedAtRoute("GetSchool", school);

CreatedAtRoute方法以一個路徑名作爲第一個參數。我懷疑你有一條名爲GetSchool的路線。這是相同控制器中的一個操作名稱。而且CreatedAtRoute不會爲未知路由拋出異常,它只會返回500個錯誤碼。

要解決此問題,使用CreatedAtAction方法,而不是CreatedAtRoute

var route = CreatedAtAction("GetSchool", school); 
板凳
0
0

我認爲這個問題是從API的結果是失敗的序列化。嘗試在單元測試中手動序列化結果並查看失敗的位置。

0
votes
answers
48 views
+10

如何通過API將文檔上傳至watson發現服務。 ASP.net

0

我正在使用以下API將文件上傳到watson發現服務。即使我提供了一個有效的類型,我也會得到不支持的文件格式的響應。 API:discovery service api如何通過API將文檔上傳至watson發現服務。 ASP.net

public async Task<ActionResult> Index() 
    { 
     using (var httpClient = new HttpClient()) 
     { 

      //ADD BASIC AUTH 
      var authByteArray = Encoding.ASCII.GetBytes("{auth key}"); 
      var authString = Convert.ToBase64String(authByteArray); 
      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authString); 

      var text = string.Empty; 
      var uri = "https://gateway.watsonplatform.net/discovery/api/v1/environments/{envid}/collections/{collectionid}/documents?version=2017-11-07"; 


      var content = new MultipartFormDataContent(); 
      var bytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Views/UploadDocument/civilwar-api1.html")); 
      var file = new StreamContent(new MemoryStream(bytes)); 
      content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/html"); 
      content.Add(new StreamContent(new MemoryStream(bytes)), "file"); 

      var response = await httpClient.PostAsync(uri, content); 
      var text1 = await response.Content.ReadAsStringAsync(); 

     } 

     return View(); 
    } 

API響應爲:{ "code" : 415, "error" : "Unsupported Media Type" }

沙发
0
0

嘗試httpClient.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

+0

儘管代碼只有答案才能解決問題,但有些解釋在理解解決方案以及將來如何解決類似問題方面有很長的路要走。 –

板凳
0
1

正如你可以看到沃森開發者雲,你可以使用.NET SDK

在此存儲庫中,您可以看到使用Watson的每項服務的examples

的方法來添加一個文件:

#region Documents 
     private void AddDocument() 
     { 
      Console.WriteLine(string.Format("
Calling AddDocument()...")); 
      using (FileStream fs = File.OpenRead(_filepathToIngest)) 
      { 
       var result = _discovery.AddDocument(_createdEnvironmentId, _createdCollectionId, _createdConfigurationId, fs as Stream, _metadata); 

       if (result != null) 
       { 
        Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented)); 
        _createdDocumentId = result.DocumentId; 
       } 
       else 
       { 
        Console.WriteLine("result is null."); 
       } 
      } 
     }