Avoiding The Use Of The Viewdata Enumerable Object In Controller?
Mar 23, 2011
I have 2 points for today I. I have a controller in which i have a public static method for getting the details for a checkbox like
[code]....
is it ok for me to use this same function like this one in the view, so that I do not need to use the viewdata object,
<%: Html.DropDownList("country", new SelectList(UserController.GetCountryLists(), "value", "countryname", "0"))%>
Also i have another query, when i use the same id & name for the radiobuttons, validation at the client side is working fine.If I use the same condition for a group of checkboxes, i get do not get the checkboxes highlighted during client validation and only during server validation, i get the error message, but the controls [checkboxes] do not have a red border indicating the error.I have used my own html helper to generate the checkboxlist as per [URL].
View 1 Replies
Similar Messages:
Mar 18, 2011
I am new to MVC3 razor and facing one issue as described below. I have one strongly typed view to display list of items and user can edit the view. When user click on a print button a popup should open to print the list . So I have to pass the current view to the popup page.
We can pass a single value as like to popup screen as "window.open('@Url.Action("ViewName", "ContollerName",new {id="ParameterValue"})'.
Is it possible to pass the current view to to popup window as a parameter like new {id="Parameter"}) ?
View 5 Replies
Feb 13, 2010
I like ASP.NET MVC, because I like to have direct access to my web site's structure. However there's 1 thing that I don't like.
In Ruby on Rails to send data from Controller to View is really easy:
# Get a user in controller
@user = User.first(:id => 1)
# Display him in a view
<%= @user.id %>
In ASP.NET MVC it's much harder
// Controller
User user = new User(1);
ViewData["user"] = user;
// View
<% User user = (MyNamespace.User)ViewData["user"]; %>
<%= user.Id %>
With this ViewData thing all benefits of static languages go away, and we waste time boxing/unboxing objects.
P.S. Don't tell me to use Model object, because this is also true for other variables like integer.
And another question:
I'm trying to implement a comfrtable access to data. Since I can't use LINQ to SQL as I use Postrgresql, I have to do it on my own. I'm tired of direct SQL queries, so I'm trying to implement something like this:
User user = User.Find("first_name" => "Bob");
View 4 Replies
Dec 28, 2010
UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development, that follows the UP(Unified Process). It uses a Grasp Controller pattern to interact with domain classes by some methods like NewSale(), AddNewItemToSale() and CloseSale. In windows form, I can instantiate a object of this class in the UI and then use its methods to perform the actions. This works well in Client apps, but when I use asp.net mvc, I cannot find a way to instantiate an object (one for each user) that was always visible for a Controller (MVC). I cannot insert as an attribute inside Controller because it always create a new one.
View 1 Replies
Feb 13, 2011
I want to pass a message from the controller to a view using Viewdata. Here is my code:
public ActionResult Create(FormCollection createPage)
{
try
{
......................
ViewData["Message"] = "Success - rec added!!!!" ;
return RedirectToAction("Index");
}
catch (Exception e)
{
ViewData["Message"] = "Exception: " + e.ToString();
return RedirectToAction("Index");
}
On my View I have:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>::><%: ViewData["Message"] %><::</h2>
<h3>==><%= ViewData["Message"] %><==</h3>
<p>
This is Index.aspx page in Controller folder
</p>
</asp:Content>
I am getting result with empty ViewData["Message"]
View 4 Replies
Nov 29, 2010
Is it possible to change Properties of ViewData.ModelMetadata in Controller?. For example, can I do the following to change the display information of the LogOnModel:
[Code]....
When I do that there is no errors but DisplayName is not change. I'm trying to localize strings to different languages and also to make some attributes of the model different depending on users roles.
View 7 Replies
Dec 9, 2010
I'm trying to display an image from the database depending on the month of the year.
The image is the sites logo and is displayed in the master page.
I cannot get the image to display on any pages except DisplayLogo.aspx and the master page when viewing DisplayLogo.aspx
i've attached all revelant code below:
[Code]....
View 5 Replies
Sep 20, 2010
I'm building a user registration wizard with ASP.NET. I'm redirecting the user to a different view for each step of the wizard. Initially, I was using TempData to store values but I realized that a couple of my values will need to persist beyond one request.
So now I'm trying to use ViewData but the behavior is different. When using TempData, I am able to render the view with the data but when I use ViewData, I get "Object reference not set to an instance of an object" when it attempts to render the view.
When I use TempData, it works, but only for the next request (by design from my understanding).
Here is my code. Any ideas on what I'm doing wrong? Also, if anyone has suggestions on to better handle a user registration wizard, I'm all ears.
ICompanyInterface service = new CompanyRepository();
bool compWebsite = service.CheckWebsite(model.Website);
if (compWebsite == true)
{
ViewData["CompanyInfo"] = service.GetCompanyInfo(model.Website);
ViewData["CompanyOffice"] = service.GetOffice(model.Website);
return RedirectToAction("SelectOffice", "RegisterCompany");
}
<asp:Content ID="Content2" ContentPlaceHolderID="LeftContent" runat="server">
<% using (Html.BeginForm()) { %>
<div>
<table>
<% foreach (var item in (ViewData["CompanyInfo"] as IList<MyApp.App.Core.Domain.CompanyInfo>))
{ %>
<tr>
<td>Website: </td><td><%: item.Website %></td>
</tr>
<tr>
<td>Company Name: </td><td><%: item.Name %></td>
</tr>
<%} %>
<% foreach (var item in (ViewData["CompanyOffice"] as IList<MyApp.App.Core.Domain.CompanyOffice>))
{ %>
<tr>
<td><%= Html.RadioButton("officeLocation", item.Id, false) %></td>
<td><%: item.Address %><br /><%: item.City + "," + item.State%><br /><%: item.Zip %></td>
</tr>
<%} %>
<tr>
<td></td>
<td>
<input type="submit" value="Add" name="addButton" />
</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Back" name="backButton" />
<input type="submit" value="Next" name="nextButton" />
</td>
</tr>
</table>
</div>
<% } %>
View 1 Replies
Feb 9, 2010
Consider the following data
<xml>
<id>10</id>
<value1>15<value1>
</xml>
I need to use this data as an input to ajax request. For eg. consider a dropdownlist change event, I need to pass these values to the controller.
sample code
//dropdown change event
$("#TestReqID").change(function() {
var id = 10;
var testResults = "abc";
var inXML = "<xml>";
inXML = inXML + "<id>" + id + "</id>";
inXML = inXML + "<value1>" + testResults + "</value1>";
inXML = inXML + "</xml>"
$.getJSON("/Home/UpdateTest/Json/" + inXML, function(data) {
//success code goes here
});
});
in HomeController
public ActionResult UpdateTest(string obj)
{
if (HttpContext.Request.IsAjaxRequest())
{
/*
Need to parse data in "obj" from ajax request
*/
IPTests test = _service.GetIPTest(Convert.ToInt32(id));
return new JsonResult { Data = new { ipTestId = "0", testResults = "" } };
}
return View(test);
}
instead of xml string is it possible to use javascript object like
[Code]....
View 2 Replies
Jul 13, 2014
I am writing a C# MVC5 internet application and am having some trouble getting the 'ApplicationUser' object in a controller that I have created.
Code:
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
ApplicationUser user = userManager.FindByNameAsync(User.Identity.GetUserId()).Result;
When I try to run this code, when a user is logged in, I am getting a null object for the 'ApplicationUser' user.
View 1 Replies
Feb 17, 2011
I'm a junior ASP.NET developer comes from Java background, so may be my question is strange.
I want to build an ascx (asp control) which accept an object as parameter for example :
1- we have a class called Device ( Contains some properties name, color , Specification (another object))
2- we have a control DeviceItem ( Contains Table to view some of the Device properties value ) and contains a property called Device
if the devices object retrieved from the Database and we have an object called device1 from Type Device
is there a direct way to pass the Device object (device1) to the DeviceItem control, some thing like :
<uc1:DeviceItem ID="DeviceItem1" runat="server" Device="THE_DEVICE_OBJECT"/>
and then bind this object to the controller, to show some properties value?
View 4 Replies
Jan 2, 2011
In my controller I fetch a list of object 'object1' which has two fields field1 & field2.Now I have a model model1 which has two fields fieldsX & fieldY.fieldX = field1fieldY = dosomething(field2 also have a view model ViewModel1 which has a single fieldpublic List<model1> model2I need to send model2 to my view
View 4 Replies
Mar 26, 2010
ss a list of objects as a paramter in an actionlinkAt the moment when I try to do this the list is always empty by the time it reaches the controller!
<%= Url.Action("ActionName", new { list = Model.ListOfObjects}) %>
public ActionResult ActionName(List<Object> list)
{
//Do stuff
}
View 3 Replies
Jun 10, 2010
Is it possible to instantiate an HtmlHelper object in a controller action in order to call HtmlHelper.EditorFor?
I would like to call HtmlHelper.EditorFor to return some partial html generated by an editor template in response to an ajax call. If I can do so I would not need to create an ascx file that otherwise would do the call to EditorFor.
View 2 Replies
Mar 4, 2011
I have the following to get the Json abject passed from the controller and populate the various textboxes in the view. However, nothing is happening even though controller is passing a valid Json object. What is wrong with this code?
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
var selectedID = $(this).val();
if (selectedID != "New Vendor Id") {
//$.post('Url.Action("DropDownChange","Refunds")', function(result) {
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
});
}
});
});
This is the code in my controller;
public JsonResult DropDownChange(string dropdownValue)
// This action method gets called via an ajax request
{
if (dropdownValue != null && Request.IsAjaxRequest() == true)
{
paymentApplicationRefund =
cPaymentRepository.PayableEntity(dropdownValue);
paymentApplicationRefund.Address1.Trim();
paymentApplicationRefund.Address2.Trim();
paymentApplicationRefund.Name.Trim();
paymentApplicationRefund.City.Trim();
paymentApplicationRefund.Contact.Trim();
paymentApplicationRefund.State.Trim();
paymentApplicationRefund.Zip.Trim();
return Json(paymentApplicationRefund,"application/json");
}
else
{
return null;
}
}
View 3 Replies
Dec 8, 2010
I have two simple classes
Trainings
[Code]....
TrainingEnrolements
[Code]....
I have variable where I am storing TrainingEnrolements
[Code]....
but I don't know how to get those trainings and store them in separate variable.
View 3 Replies
Nov 29, 2010
I have a table "OSTAN" with two columns "ID" (Key index) and "NAME". I am trying to construct a linq query to select the Name for a specific ID. I have not luck trying to construct the where clause. Here what I have so far:
using (XeledsEntities db = new XeledsEntities())
{
string SelectedName = db.Ostans.Name.Where( Ostan=> Ostan.Equals(Request.QueryString["Ostan"])).FirstOrDefault();
}
Can anybody construct this where clause to set the Selected Name?
View 2 Replies
Mar 21, 2011
The following code works fine for converting an XML data set to be enumerable for Linq.
'Query webservice for data
Dim propertyInfo As String = myService.GetProperty(userName, password, Acct)
' Create a new DataSet.
[code]...
However, it does not retain the xml tags in the Linq enumerablerable dataset ('newDataSet2"). I don't think I can rely on the array index order as being the same everytime, so this would obviously cause a problem if I'm trying to align the array items up to my database fields. How can I make newDataSet2 retain the XML tags (column headings) to insure I know what data field each array item belongs to?
View 1 Replies
Dec 21, 2010
I am creating one Json array object and trying to pass it in MVC controller action method but i am getting null paramerter; as per my knowledge json only maps .net primitive datatypes.... so it assign null value.
Note: when i have look at request object i found that there are three parameter of created array. But how to get that value as parameter of function?
View 2 Replies
Aug 7, 2010
I want to iterate through HtmlTable (Server Side) in ASP.NET 3.5.
foreach (System.Web.UI.HtmlControls.HtmlTableRow trow in someTable)
{
var x = trow.InnerText;
}
I received an error message that "System.Web.UI.HtmlControls.HtmlTable" does not contain a definition for GetEnumerator.
How to write an extension method or alternative to make HtmlTable as enumerable row collection?
View 2 Replies
Feb 5, 2010
Existed MyControl1.Controls.OfType<RadioButton>() searches only thru initial collection and do not enters to children.
Is it possible to find all child controls of specific type using Enumerable.OfType<T>() or LINQ without writing own recursive method? Like this.
View 1 Replies
Jan 28, 2011
I'm trying to follow the demo from this link to add a jqGrid to an MVC app.
I have a table named Companies that I'm trying to display in a grid. A Company simply contains an ID and a Name.
I'm running into an error in my controller function:
public JsonResult DynamicGridData(string sortIndex, string sortOrder, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var companies = companiesRepository.Companies.OrderBy(sortIndex + " " + sortOrder).Skip(pageIndex * pageSize).Take(pageSize);
//Error here
...
}
I'm getting an error on the line that is calling OrderBy():
The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
I really have no idea what the error means, and I haven't been able to find an explanation. I'm not sure what is causing this error on a simple OrderBy function.
View 2 Replies
Jan 18, 2011
I am generating an output on a webpage in a format like this
({"1":"Jeff","2":"Tom","3":"Michael",})
For this, basically this is the code I am using
Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?
My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)
View 8 Replies
Feb 24, 2011
I recently read an article on making ASP.NET sessions more secure here and at first it seems really useful.
Previously I had been storing the user's IP address in the session, then making sure in every subsequent request that the requesting IP was equal to the stored IP.
The code in the article also protects the session by checking the IP address, except it stores a hashed message authentication code containing the user's IP as part of the session cookie. It creates a hashed MAC twice every request, which I imagine would slow things down a little.
I can already see a potential flaw in their code: if you were to somehow get a hold of the key used to generate the MAC, you could then generate a valid MAC with your own IP - you wouldn't even have to fake the IP the session was started on.
It seems like an overly-complex solution to a simple problem which not only incurs a larger overhead but also is more susceptible to attack than the trivial method - unless I'm completely missing the point.
So, why would this approach be any more secure than the more simple approach that I had been using?
As a slight aside, the author also states that you shouldn't use the whole IP address in the comparison, as some user's IPs change every request if they are behind a proxy. Is this still the case if you check X_FORWARDED_FOR?
View 1 Replies
Jan 31, 2011
I'm having issues with an ASP.net site (framework 3.5, IIS6 ) having very slow 'first hit' response times. I'm guessing that the issue is to do with the app pool recycling and having to warm up.
I got to thinking. As part of the site I have a HTTP module that spins up a 'never ending loop' on a separate thread which periodically (every 5 seconds) calls an sproc on SQL to make sure the database is still there. I'm wondering if a similar approach might work to get the site to make an HTTP request to "itself" as a keep alive.
My question is, before I go and do this, can anyone think of any reason why it won't work? For example, something like "oh no... ASP.Net will figure out that you're playing with yourself and not go through the whole page lifecycle... etc etc".
View 1 Replies