I want to do the menu page in a MVC project, there I need to populate some GridViews with different data from some models. First I created some datasets which contain the datatables; in the controller i call the index view which shows the main page.
public ActionResult Index()
{
..........
return View();
}
Index view
#{ Layout = "~/Views/Shared/_mainLayout.cshtml"; }
#{Html.RenderPartial("TicketsPartial");}
#Html.DevExpress().PageControl(s =>
{
s.Name = "tabcontrol";
s.TabPages.Add(tabPage =>
{
tabPage.Text = "Inbox";
tabPage.SetContent(() =>
{
Html.RenderPartial("InboxPartial");
});
});
s.TabPages.Add(tabPage =>
{
tabPage.Text = "Sent";
tabPage.SetContent(() =>
{
Html.RenderPartial("SentPartial");
});
});
}).GetHtml()
So I'm trying to use the Html.RenderPartial to call some partial views... here's the code in InboxPartial
#model DataModels.Email.DS_EmailMessages.DT_com_mail_messagesDataTable
#Html.DevExpress().GridView(s =>
{
s.Name = "Inbox";
s.KeyFieldName = "idticket";
s.Width = System.Web.UI.WebControls.Unit.Percentage(100);
}).Bind(Model).GetHtml()
So first I give the model to the view... the datatable from which the data should be loaded and I bind it to the gridview...
The thing is that this isn't displaying any data and also any column...and I really can't understand why... for example if I give the datatabel as a parameter in the controller like this:
public ActionResult Index()
{
..........
return View(dS_Tickets.DT_com_consultant_tickets);
}
And i erase the model from the views so there will not be any conflict, each partialview will show the columns and data taken from the datatabel, but only from that one table that I gave as a parameter.. I need to take the data from different tables... how can I do this?
Note: I'm using an extension called DevExpress v.12
Related
im doing an MVC with CRUDS.
this is my code.
[HttpPost]
public ActionResult Create([Bind(Include = "FileStatusID, Name, MinValue, MaxValue")] fileStatusModel FILeStatusModel, TBL_FileStatus tBL_FileStatus) //include tem os valores que vamos inserir na view
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
if (ModelState.IsValid)
{
TBL_FileStatus item = new TBL_FileStatus()
{
Name = FILeStatusModel.Name,
MinValue = FILeStatusModel.MinValue,
MaxValue = FILeStatusModel.MaxValue,
Ative = true,
CreateDate = DateTime.Now,
CreateBy = userID
};
db.TBL_FileStatus.Add(item);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
I want to create a status with special conditions.
I have a table with ID, status, minvalue and maxvalue and have an interval of numbers in those values.
I want to create another status out of the range of those numbers.
ex: minvalue: 20 maxvalue: 40
So.. When i create a new status, if i put numbers inside that range, its say a message like "already exist in that range", if not, it creats de status.
thanks
1. Rendering layout page from ActionResult (using Controller. View extension method)
The Controller. View method has two extension methods, using these
extension methods we can pass a master page (layout page) name and
render a layout page based on a condition.
Example Code
public ActionResult About()
{
return View("About","_otherLayout");
}
public ActionResult OtherAbout()
{
string myName = "Jignesh Trivedi";
return View("About", "_otherLayout", myName);
}
2. Using _ViewStart.cshtml Page
The Controller. View method has two extension methods, using these
extension methods we can pass a master page (layout page) name and
render a layout page based on a condition.
Using the _ViewStart.cshtml page, we can change the layout page based
on a condition.
Example Code
#{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string layout = "";
if (controller != "Home")
{
layout = "~/Views/Shared/_otherLayout.cshtml";
}
else
{
layout = "~/Views/Shared/_Layout.cshtml";
}
Layout = layout;
}
We can also create multiple _ViewStart.cshtml pages. The file
execution is dependent upon the location of the file within the folder
hierarchy and the view being rendered. The MVC Runtime will first
execute the code of the _ViewStart.cshtml file located in the root of
the Views folder.
3. Define the Layout page in each view
We can override the default layout rendering by setting the Layout
property of the View using the following code.
#{
Layout = "~/Views/Shared/_otherLayout.cshtml";
ViewBag.Title = "About Us";
}
As presented in the article by : Jignesh Trivedi at
https://www.c-sharpcorner.com/UploadFile/ff2f08/rendering-layouts-base-on-condition-in-Asp-Net-mvc/
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 = "" })
In my main INV_Assets controller of my MVC5 app, I have an method for Edit() which passes several populated SelectLists() via the ViewBag to allow users to select from all available entities for the relevant list in the other tables of my Database -- Note, if there is a better practice than passing this through the ViewBag, please feel free to guide me to a better way.
// GET: INV_Assets/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
INV_Assets iNV_Assets = await db.INV_Assets.FindAsync(id);
if (iNV_Assets == null)
{
return HttpNotFound();
}
ViewBag.Location_Id = new SelectList(db.INV_Locations, "Id", "location_dept", iNV_Assets.Location_Id);
ViewBag.Manufacturer_Id = new SelectList(db.INV_Manufacturers, "Id", "manufacturer_description", iNV_Assets.Manufacturer_Id);
ViewBag.Model_Id = new SelectList(db.INV_Models, "Id", "model_description", iNV_Assets.Model_Id);
ViewBag.Status_Id = new SelectList(db.INV_Statuses, "Id", "status_description", iNV_Assets.Status_Id);
ViewBag.Type_Id = new SelectList(db.INV_Types, "Id", "type_description", iNV_Assets.Type_Id);
ViewBag.Vendor_Id = new SelectList(db.INV_Vendors, "Id", "vendor_name", iNV_Assets.Vendor_Id);
return View(iNV_Assets);
}
My lists currently populate fine, but for ease of use I want to insert a value of "Add New" into each list, that when clicked will open pop-up (partial view?) of my relevant Create() View for the relevant entity. For example, if the Locations SelectList() has "Add New" clicked, I want to open my Create view for Locations.
Can anyone offer an example of how to do this?
I've been looking for how to insert a new value into the SelectList() but most of what I seem to be coming across is using the example of forgoing the SelectList() instead for an Html.DropDownList(), though I'm not sure why?
The SelectList class inherits IEnumerable<SelectListItem>, which are used to populate drop down lists.
Given a ViewModel object that has the following property:
public SelectList Options
{
get
{
var items = Enumerable.Range(0, 100).Select((value, index) => new { value, index });
SelectList s = new SelectList(items, "index", "value");
return s;
}
}
public int SelectedOption { get; set; }
The view:
#Html.DropDownListFor(m => m.SelectedOption, Model.Options, "Add New", new { #class = "form-control" })
In order to do what you want regarding the popup, you probably need some javascript to deal with this.
If you don't want the "Add New" in the DropDownListFor() you would need to add it manually to your collection before returning it to the view.
Hope this helps.
Here is the part of the UI that I'm trying to update:
<label>Country</label>
<select name="country" data-bind="options: $parent.CountryList, optionsCaption: '- Select -'"></select>
As you can see, I tried $parent.CountryList because I was hoping that would refer to the CountryList in the code behind. Here is a snippet of the Page_Load function where I'm storing data from a database into a list of countries:
using (CCGEntities db = new CCGEntities())
{
List<Country> CountryList = db.Countries.ToList();
}
The goal is to take the list of countries and have them populate the select element as a dropdown menu. I tried mimicking the binding for asp:DropDownList but the code behind didn't pick up on an ID attribute for the select element. Would I be better of doing this with asp:DropDownList?
That is not how you must do it in ASP.NET. You must create ViewModels and bind them using ko.applybindings(viewModel, YOUR_HTML_ELEMENT_ROOT). In order to do that, the model should either:
a) Be serialized at run time by the server and dumped into a javascript variable
or b) Fetched dynamically with javascript and then apply the binding
A complete example of how to achieve this with Entity Framework, ASP.NET and Knockout is available here.
Dropdownlist population with knockout.js can seem a bit tricky at first. I ve implemented a knockout binder to make this easier:
ko.extenders.autoOptions = function (target, type) {
target["Options"] = [];
console.log("getting options for type: " + type);
target.Options = ApplicationGateway.getOptions([ApplicationName.Api.Options]+type);
return target;
};
This binder can be used in the following manner in your javascript models:
self.Gender = ko.observable().extend({ autoOptions: 'GENDER', required: { message: 'Gender is required' } });
Which results in the following template usage:
<select data-bind="options: Gender.Options,
value: Gender,optionsText: 'Text',optionsValue: 'Value'">
</select>
My Asp.Net Web API Options Controller looks like this:
public class OptionsController : ApiController
{
private ResourceManager _resourceManager;
private CultureInfo _cultureInfo;
[HttpGet]
[Route("api/Options/{type}")]
public List<ListItem> List(string type)
{
_resourceManager = new ResourceManager("Application.Resources.RESOURCE", typeof(APPLICATION).Assembly);
_cultureInfo = new CultureInfo(Application.CurrentSession.User.LanguageSelected);
switch (type.ToUpper())
{
case "GENDER": return Gender();
...
}
return new List<ListItem>();
}
private List<ListItem> Gender()
{
var items = new List<ListItem>
{
new ListItem(_resourceManager.GetString("Label_Gender_Male", _cultureInfo),Domain.Enums.Gender.Male.ToString()),
new ListItem(_resourceManager.GetString("Label_Gender_Female", _cultureInfo), Domain.Enums.Gender.Female.ToString()),
};
return items;
}
}
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>