I am new to asp.net , C# and building an MVC application based on the popular Music Store application.
I have my basic navigation ready and I have reached a point where I am drawing a complete blank. Basically, my asp page displays a SQL query (which is saved in SQL DB on same machine)
Need:
I need to have a button next to this query which when clicked, connects to another DB through OLEDB, and runs the query and shows result in a pop up window.
Questions:
How do I pass the query (which is being fetched from DB) as a parameter to code below and How do I make the results pop up in a window.
Can you please point me in correct direction. The code below is from a stand alson asp page which i used for testing connections etc. basically i need to pass the query as a parameter (replacing query seen below) and have the result in a pop window.
<%# Import Namespace="System.Data.OleDb" %>
<%# Import Namespace="System.Data.Odbc" %>
<script runat="server">
sub Page_Load
Dim dbconn, sql, dbcomm, dbread
dbconn = New OleDbConnection("Provider=xxxx;Password=xxxx;User ID=xxxx;Data Source=xxxx;Initial Catalog=xxxx;Port=xxxx;")
dbconn.Open()
sql = "Select ID from TABLE1"
dbcomm = New OleDbCommand(sql, dbconn)
dbread = dbcomm.ExecuteReader() <%-- Call this method within oledbcommand--%>
If dbread.Read = False Then
MsgBox("No Data Check")
Else
Response.Write("<table>")
Do While dbread.Read()
Response.Write("<tr>")
Response.Write("<td>")
Response.Write(dbread(0))
Response.Write("</td>")
Response.Write("</tr>")
Loop
Response.Write("</table>")
End If
dbconn.Close()
end sub
</script>
ADDITIONAL DETAILS
CONTROLLER CLASS
.
.
public ActionResult DisplayResult(String Qry)
{
List<QuerySet> QueryToExecute = new List<QuerySet>();
return View(QueryToExecute);
VIEW that provides this contoller with DATA, this is query that is fetched from my SQL DB and should be executed to a separate DB on a separate server.
<ul>
#foreach (var ShowQueries in Model.Queriess)
{
<li>
#Html.ActionLink(ShowQueries.Query, "DisplayResult", new { Qry = ShowQueries.Query })
</li>
}
ISSUE:
How should I use a view named 'DisplayResult' which handles the query fetched by view above and executes it agaisnt another DB.
I was hoping I can use a Webform view rather than a razor view but either way i am not able to pass the parameter
Any ideas are appreciated
The point of MVC is to move data connections out of the View (aspx page) and into a Controller.
Read some more MVC tutorials, and buy a book or two. You should actually populate the data into a viewmodel on the controller, and then pass that viewmodel to the view. This way, the view knows nothing about how to get the data -- it already got it from the controller.
Views should have the responsibility of displaying data to users over the web, not getting the data or manipulating it directly.
With that aside, here is how you would do it:
Pass the query as a string to an Action Method on a Controller (using HTTP POST or GET) using AJAX (i.e. jQuery $.ajax() method).
Have the action method return the HTML for your popup window, using a Partial View. You could also return Json, but I think HTML / partial view would be easier in this case. This is the method that will do your OLE DB connection, and execute the query.
In your $.ajax() success function callback, write javascript that will popup a new dialog with the partial view HTML that was returned by the controller action method.
You could create a class to hold the data you want to display:
namespace sample {
class viewList
{
public string field1 {get;set;}
...
}
}
and create a list to hold your results in your controller:
List<viewList> theList = new List<viewList>();
//Populate dbread here...
while (dbread.Read())
{
viewList listData = new viewList();
listData.field1 = (dataType)dbread[0]; //Convert to your data type
theList.Add(listData);
}
and pass this to the view:
return view(theList);
Then in your model (of model type viewList) display your results in a table:
#model sample.viewList
<table>
#foreach (var item in Model)
{
<tr>
<td>#item.field1</td>
</tr>
}
</table>
ALTERNATIVE
To display in popup, put the list into the ViewBag like this:
List<viewList> theList = new List<viewList>();
//Populate dbread here...
while (dbread.Read())
{
viewList listData = new viewList();
listData.field1 = (dataType)dbread[0];
theList.Add(listData);
}
ViewBag.Items = theList;
Then in your view:
<script type="text/javascript">
$(function() {
var array = #Html.Raw(Json.Encode(ViewBag.Items));
//Construct your table using the array here...
alert(theConstructedTable);
});
</script>
Related
I'm a newbie to Razor and Asp.Net. I'm mostly a Winforms developer. I must say I don't like what I've been seeing in ASP, over complicated to say the least. Anyways, I want to take the value from a #Html.TextBox and store it to a variable. I've searched on here an can't find a solution. There has to be a simple way of doing this.
I've been trying to pull the value out with Request.Froms but keeps crashing
#Html.TextBox("test")
#Html.TextBox("test2")
#{
var z = Request.Form["test"];
var x = Request.Form["test2"];
}
All I want is to store the inputted value to z and x. Meaning if I input 2 into test and 3 in to test2 I want z = 2 and x = 3.
Depending on your use case, there are several ways to get the values:
If you need the values in the frontend (e.g. without reload of the page), you can use JavaScript/jQuery to get the values of the textbox. That is because when the user interacts with the inputs, the Razor code already has been executed and turned e.g. into HTML (also see this question). You could set your variables when the inputs are changed using jQuery.change() as follows:
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script type="text/javascript">
var x = null;
var y = null;
$(document).ready(function () {
$("#test").change(function () {
x = $("#test").val();
alert(x);
});
$("#test2").change(function () {
y = $("#test2").val();
alert(y);
});
});
</script>
If it is sufficient to have the values after a reload of the page, you can put the inputs in a form, and submit that to the controller, where the values are available in the request or using model binding (see this tutorial for an example of how to do that in ASP.NET Core MVC). A basic example for your scenario:
In the view:
<form asp-controller="Home" asp-action="Test" method="post">
#Html.TextBox("test")
#Html.TextBox("test2")
<button type="submit">Submit</button>
</form>
And in the Home controller (note that here you can access the inputs using the Request):
[HttpPost]
public ActionResult Test()
{
var x = Request.Form["test"].First();
var y = Request.Form["test2"].First();
return RedirectToAction("Index");
}
I have multiple static htmls stored in the /Content/ file. I have a method in the controller which displays these static html files.
public ActionResult GetHTML(int sectionId)
{
var result = new FilePathResult($"~/Content/files/{sectionId}.html", "text/html");
return result;
}
I have no view for this method, but I'd like to create one and to include a button which allows me to navigate to the next/previous static html.
Any help is highly appreciated.
You can create a regular view with a FilePathResult as its model.
If the model is not null in the view then you can create a hyper link in the view from result:
Next Page
I have table that contains data and links that open partial view with related data. I use jquery datatable, when I'm on first page everything works fine, but if I go to the next pages and cliked link I dont have beauty partial view, page return only source code from partial view file and skips _Layout.cshtml.
What should I do to make the code work correctly?
Controller:
public ActionResult KsiazkiZlecenia(int zlecKompletID, string magazynID)
{
SystemMagazynowy ksiazki = new SystemMagazynowy();
var listaksiazek = ksiazki.PobierzInfoKsiazek(zlecKompletID, magazynID);
ViewBag.ksiazki = listaksiazek;
return PartialView();
}
Link:
#Html.ActionLink("Książki", "KsiazkiZlecenia", new { zlecKompletID = item.ZlecKompletID, magazynID = ViewBag.MagazynID }, new { #data_modal = "" })
I didn't understand how does server-side pagination works with MySql and Datatable in a C# MVC.
I created a Controlled in C#, in which I established the connection with a MySql database (I followed this example in order to do that):
public ActionResult connectDB()
{
const string DB_CONN_STR = "Server=MyServer;Port=MyPort;Uid=MyUid;Database=MyDB;";
MySqlConnection cn = new MySqlConnection(DB_CONN_STR);
try
{
string sqlCmd = "select * from t_documento";
MySqlDataAdapter adr = new MySqlDataAdapter(sqlCmd, cn);
adr.SelectCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
adr.Fill(dt); //opens and closes the DB connection automatically !! (fetches from pool)
return Content(JsonConvert.SerializeObject(dt).ToString());
}
catch (Exception ex)
{
Console.WriteLine("{oops - {0}", ex.Message);
return Content(ex.ToString());
}
finally
{
cn.Dispose(); // return connection to pool
}
}
However, in this way, I retrieve all the records stored in that table, but I want to fill the Datatable (the inizialization of my datatable is located in a cshtml page) by implementing the pagination.
I read a lot of articles but I didn't found a clear example with a MySql DB.
Can someone help me, please?
Thank you!
Try this Example of server side pagination.
/Controllers/ProductController.cs
public class ProductController : Controller
{
public object Index(int? page)
{
var products = MyProductDataSource.FindAllProducts(); //returns IQueryable<Product> representing an unknown number of products. a thousand maybe?
var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
var onePageOfProducts = products.ToPagedList(pageNumber, 25); // will only contain 25 products max because of the pageSize
ViewBag.OnePageOfProducts = onePageOfProducts;
return View();
}
}
/Views/Products/Index.cshtml
#{
ViewBag.Title = "Product Listing"
}
#using PagedList.Mvc; //import this so we get our HTML Helper
#using PagedList; //import this so we can cast our list to IPagedList (only necessary because ViewBag is dynamic)
<!-- import the included stylesheet for some (very basic) default styling -->
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<!-- loop through each of your products and display it however you want. we're just printing the name here -->
<h2>List of Products</h2>
<ul>
#foreach(var product in ViewBag.OnePageOfProducts){
<li>#product.Name</li>
}
</ul>
<!-- output a paging control that lets the user navigation to the previous page, next page, etc -->
#Html.PagedListPager( (IPagedList)ViewBag.OnePageOfProducts, page => Url.Action("Index", new { page }) )
What is the best approach to take when converting a basic ActionResult to JSON objects and rendering them in a PartialView? My objective is to modify the application so that instead of the page rendering only the comments in the db at the time of the page request to a type of data service that updates thePartialView to add any incoming comments that may have been posted since the last page request. I think the solution I am looking for will use OData in json format and then bind that data using knockout.js, but not sure.
Here is the Controller ActionResult which returns an IEnumerable list of objects from the repository to a PartialView:
[ChildActionOnly]
public ActionResult GetCommentsById(int AId = 0)
{
if (AId == 0)
return HttpNotFound();
return PartialView("_CommentsPartial",
_unitOfWork.ArticleRepository.GetCommentsByArticleId(AId));
}
Here is a snippet of the PartialView to keep things short:
#model IEnumerable<BlogSite.Models.Comment>
#using BlogSite.Helpers;
<ul id="comments-list">
#{
foreach (var comment in Model)
{
<!--Grabs Parent Comment and then all replies w/ParentCommentId b4 grabs new Parent Comment -->
if (comment.isRoot && comment.ParentCommentId == null)
{
<!-- Comment -->
int counter = 0; foreach (var c in Model) { if (c.ParentCommentId == comment.CommentId) { counter += 1; } }
<li id="#comment.CommentId" itemscope itemtype="http://schema.org/UserComments" class="comment-container" tabindex="#comment.CommentId">
Then I call it from the Details view:
<div id="comments-panel" class="panel-box">
<div class="show-comments"><div id="upNdown"></div><span id="showNhide">Show Comments</span></div><br /> <br />
<div id="comments-partial" style="display:none;">
#Html.Action("AddComment", "Comment", new { AId = Model.ArticleId })
#Html.Action("GetCommentsById", "Article", new { AId = Model.ArticleId })
</div>
</div>
How can I make this conversion as painless as possible? Thanks in advance!
I think I gather from your question that the controller already did its work and that you simply want to "consume" the data output from it as if it were an AJAX request using the same js code. You can do this fairly easily by just serializing the data in the model using the Newtonsoft Json.NET api and extensions provided by Forloop.HtmlHelpers. These can be installed as nuget packages if you haven't already.
First, you would place this in your partial view
Note: If you don't want to install the Newtonsoft package you can replace JsonConvert.SerializeObject with the System.Web.Helpers method Json.Encode
#{
using (var context = Html.BeginScriptContext())
{
Html.AddScriptBlock("var jsonData=" + JsonConvert.SerializeObject(Model) + ";");
}
}
Then in your layout page, to ensure that your script block is rendered at the appropriate time, add this call to Html.RenderScripts
#Scripts.Render("~/bundles/jquery")
#*Add any other dependency scripts*#
#Html.RenderScripts()
#RenderSection("scripts", required: false)
This is why you need the Forloop.HtmlHelpers package, these extension methods help mitigate out-of-order script code getting rendered in the partial view before jQuery or anything else has started up.
Hope that helps