Search Results

Search found 934 results on 38 pages for 'actionresult'.

Page 32/38 | < Previous Page | 28 29 30 31 32 33 34 35 36 37 38  | Next Page >

  • how can i replace an image (inside a div) through jquery and ajax.

    - by oo
    I am trying to click on an image and change it to another image through jquery. When i step through the below code, on the serverside, the controller action fires and on the client side, i can see the correct html return in firebug watch window but the image doesn't change at all. any idea why this div is not updating? original div: <div class="inlineDiv" toggle="off" id="22"><img src="../../images/vote-favorite-off1.png" border="0"></div> jquery code: $(document).ready(function() { $('div.inlineDiv').live('click', function() { var id = $(this).attr("id"); var toggle = $(this).attr("toggle"); var url = '/Tracker/Update?id=' + id + '&toggle=' + toggle; $.get(url, function(data) { $(this).html(data); }); }); }); controller action: public ActionResult Update(int id, string toggle) { if (toggle == "off") { return Content("<img src='../../images/vote-favorite-on1.png' border=0'>"); } return Content("<img src='../../images/vote-favorite-off1.png' border=0'>"); }

    Read the article

  • Passing Object From Controller to JavaScript JQuery

    - by TMan
    This is driving me crazy. All I'm trying to do is to pass in a Id to a ActionMethod which is working and have an Object be returned to the javascript. Then in javascript, I want to be able to say something like..Objec.Property, ie/ Student.Name, or Student.GPA. Any help is appreciated. I tried json but couldn't get that to work either. ActionResult: [AcceptVerbs(HttpVerbs.Get)] public Epic GetEpicPropertyDetails(int id) { var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id)); return Epictemplist.SingleOrDefault(); } javascript: <script type="text/javascript"> $(document).ready(function () { $(".ListBoxClass").click(function (event) { var selectedid = $(this).find("option:selected").val(); event.preventDefault(); $.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) { $(".TimeClass").val(result); }); }); }); </script> result.Name is obviously wrong I just dont know how to call this the right way.

    Read the article

  • MVC JsonResult with the [Authorize] attribute going to Logon but not displaying the view

    - by likestoski
    I am seeing odd behavior with MVC 3 methods that return a JsonResult when used with the Authorize attribute. What looks like happens is the Authorize is correctly evaluated when I am not logged in but instead of redirecting to the logon form the Json response is the logon form. Is there an addition attribute that directs the response to not return a value but instead redirect the user to the logon form, preferebly with the correct returnUrl value? What I did as a demo was to setup a new MVC3 site and added AspNetMembership to my DB using the aspnet_regsql.exe command. All that is setup and logging me in correctly. The behavior of the JsonResult doesn't seem right and I'm hoping I have just missed an attribute to make it work properly. Any help is greatly appreciated, thanks in advance. Here is the Account Controller (leaving out the Post action which is not part of this question). public class AccountController : Controller { public ActionResult LogOn() { return View(); } [Authorize] public JsonResult AuthorizedAction() { return Json("Only returns if I am authorized"); } } Here is the Html markup: <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnTest").click(function () { $.ajax({ type: "POST", url: "Account/AuthorizedAction", data: {}, success: function (result) { $("#testMe").html(result); }, error: function (result) { $("#testMe").html('Something broke in the ajax request'); } }); }); }); </script> <input type="button" id="btnTest" value="Test me" /> <div id="testMe">I have initial text</div> The Result: 1) When logged in I get 'Only returns if I am authorized' in my test div 2) When not logged and I have a break point in my Logon() method I see this value Request["returnUrl"] "/Account/AuthorizedAction" The test div I have displays the logon form :) this seems like I'm just not handling this properly.

    Read the article

  • Trying to edit an entity with data from dropdowns in MVC...

    - by user598352
    Hello! I'm having trouble getting my head around sending multiple models to a view in mvc. My problem is the following. Using EF4 I have a table with attributes organised by category. Couldn't post an image :-( [Have a table called attributes (AttributeTitle, AttributeName, CategoryID) connected to a table called Category (CategoryTitle).] What I want to do is be able to edit an attribute entity and have a dropdown of categories to choose from. I tried to make a custom viewmodel public class AttributeViewModel { public AttributeViewModel() { } public Attribute Attribute { get; set; } public IQueryable<Category> AllCategories { get; set; } } But it just ended up being a mess. <div class="editor-field"> <%: Html.DropDownList("Category", new SelectList((IEnumerable)Model.AllCategories, "CategoryID", "CategoryName")) %> </div> I was getting it back to the controller... [HttpPost] public ActionResult Edit(int AttributeID, FormCollection formcollection) { var _attribute = ProfileDB.GetAttribute(AttributeID); int _selcategory = Convert.ToInt32(formcollection["Category"]); _attribute.CategoryID = (int)_selcategory; try { UpdateModel(_attribute); (<---Error here) ProfileDB.SaveChanges(); return RedirectToAction("Index"); } catch (Exception e) { return View(_attribute); } } I've debugged the code and my _attribute looks correct and _attribute.CategoryID = (int)_selcategory updates the model, but then I get the error. Somewhere here I thought that there should be a cleaner way to do this, and that if I could only send two models to the view instead of having to make a custom viewmodel. To sum it up: I want to edit my attribute and have a dropdown of all of the available categories. Any help much appreciated!

    Read the article

  • Does anyone know why jquery dialog is showing stale content on ajax update ?

    - by oo
    I have a series of links and when i click on a link i want to show a dialog with detail information. This detail is returned from an jquery ajax request. I am using the following code below to show a partial result through ajax onto a jquery dialog. Here is the jquery code: $(document).ready(function() { $('a.click').live('click', function() { var url = '/Tracker/Info?id=' + $(this).attr("id"); var dialogOpts = { modal: true, bgiframe: true, autoOpen: false, height: 600, width: 450, overlay: { opacity: 0.7, background: "black" }, draggable: true, resizeable: true, open: function() { //display correct dialog content $("#dialogDiv").load(url); } }; $("#dialogDiv").dialog(dialogOpts); //end dialog $("#dialogDiv").dialog("open"); }); }); Here is my controller action code: public ActionResult Info(int id) { return PartialView("LabelPartialView", _Repository.GetItem(id)); } Here is the issue: When i click this the first time (lets say i send id = 1234) it works fine. When i click on another item (lets say i send id = 4567) it shows the content from 1234 still. Which i click this second item again (again its 4567), then it will show the content from 4567. Does anyone know why it might not be refreshed the first time? Is this a timing issue?

    Read the article

  • How can I keep the the logic to translate a ViewModel's values to a Where clause to apply to a linq query out of My Controller?

    - by Mr. Manager
    This same problem keeps cropping up. I have a viewModel that doesn't have any persistent backing. It is just a ViewModel to generate a search input form. I want to build a large where clause from the values the user entered. If the Action Accepts as a parameter SearchViewModel How do I do this without passing my viewModel to my service layer? Service shouldn't know about ViewModels right? Oh and if I serialize it, then it would be a big string and the key/values would be strongly typed. SearchViewModel this is just a snippet. [Display(Name="Address")] public string AddressKeywords { get; set; } /// <summary> /// Gets or sets the census. /// </summary> public string Census { get; set; } /// <summary> /// Gets or sets the lot block sub. /// </summary> public string LotBlockSub { get; set; } /// <summary> /// Gets or sets the owner keywords. /// </summary> [Display(Name="Owner")] public string OwnerKeywords { get; set; } In my controller action I was thinking of something like this. but I would think all this logic doesn't belong in my Controller. ActionResult GetSearchResults(SearchViewModel model){ var query = service.GetAllParcels(); if(model.Census != null){ query = query.Where(x=>x.Census == model.Census); } if (model.OwnerKeywords != null){ query = query.Where(x=>x.Owners == model.OwnerKeywords); } return View(query.ToList()); }

    Read the article

  • nullable bool is being passed to the controller null all the time regardless of the value

    - by user1807954
    I'm trying to pass a nullable bool to my controller. But when I pass the bool value from my view to the controller, it's being passed null all the time regardless of the value it has in my view. Here is my view: @model Cars.Models.Car @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "CategoryFormID"})) { <label>Convertible:</label> <input type="checkbox" id="ConvertibleID" name="convertible"/> <button type="submit" name="submit" value="search" id="SubmitID">Search</button> } And my controller: [HttpPost] public ActionResult Index(bool? convertible){ var cars = from d in db.Car select d; if (convertible.HasValue) { cars = cars.Where(x => x.Convertible == convertible); } return View("SearchResult", cars); } I also have other fields such as drop down lists and text fields, but they're being passed flawless. Any help would be really appreciated. Update: Thank you for your fast responds. However, I did try giving it a value="True" as you guys suggested. There is only 2 options now: null and true. But my intention is to use nullable bool to have three options: null (when user doesn't touch the checkbox), true(checked) and false(unchecked). I know it sounds not smart and silly, but I'm just trying to figure out how nullable bool is working, and what is the intention of having such a thing in C# (I'm new with C#). I was wondering if it is possible to do so with just checkbox and without the use of dropdownlist or radio buttons.

    Read the article

  • better way of showing File Upload Errors?

    - by coure06
    Model: public class EmailAttachment { public string FileName { get; set; } public string FileType { get; set; } public int FileSize { get; set; } public Stream FileData { get; set; } } public class ContactEmail: IDataErrorInfo { public string Name { get; set; } public string Email { get; set; } public string Message { get; set; } public EmailAttachment Attachment { get; set; } public string Error { get { return null; } } public string this[string propName] { get { if (propName == "Name" && String.IsNullOrEmpty(Name)) return "Please Enter your Name"; if (propName == "Email"){ if(String.IsNullOrEmpty(Email)) return "Please Provide an Email Address"; else if(!Regex.IsMatch(Email, ".+\\@.+\\..+")) return "Please Enter a valid email Address"; } if (propName == "Message" && String.IsNullOrEmpty(Message)) return "Please Enter your Message"; return null; } }} And my controller file [AcceptVerbs(HttpVerbs.Post)] public ActionResult Con(ContactEmail ce, HttpPostedFileBase file) { return View(); } Now the Problem From the form i am getting Name,Email, Message and uploaded file. I can get validation errors automatically for Name,Email,Message using public string this[string propName]. How can i show validation errors if Attachment.FileSize 10000? If i write its code in public string this[string propName] i alwasy getting Attachment null. How can i fill Attachment Object of ContactEmail so that i can manage all errors on same place?

    Read the article

  • MVC3 html.TextBox

    - by BigTommy79
    I have login view that takes a LoginPageViewModel: public class LoginPageViewModel : PageViewModel { public string ReturnUrl { get; set; } public bool PreviousLoginFailed { get; set; } public LoginFormViewModel EditForm { get; set; } } which is rendered in the view. When a user tries to log in I only want to post the LoginFormViewModel (Model.EditForm) to the controller: public ActionResult Login(LoginFormViewModel loginDetails) { //do stuff } Using Html.TextBox I can specify the name of the form field manually 'loginDetails.UserName' and post back to the controller and everything works. @model Web.Controllers.User.ViewModels.LoginPageViewModel @using (Html.BeginForm()){ @Html.Hidden("loginDetails.ReturnUrl", Model.ReturnUrl) @Html.LabelFor(x => x.EditForm.UserName, "User Name:") @Html.TextBox("loginDetails.UserName", Model.EditForm.UserName) @Html.ValidationMessageFor(x => x.EditForm.UserName) ..... But what I want to do is to use the staticaly typed helper, something like: @Html.TextBoxFor(x => x.EditForm.UserName) But I'm unable to get this to work. Are you only able to post back the same model when useing the strongly typed helpers? Is there something I'm missing on this? Intellisense doesn't seem to give any clues such as a form field string.

    Read the article

  • Post JSON array to mvc controller

    - by Yustme
    I'm trying to post a JSON array to a mvc controller. But no matter what i try, everything is 0 or null. I have this table that contains textboxes. I need from all those textboxes it's ID and value as an object. This is my java code: $(document).ready(function () { $('#submitTest').click(function (e) { var $form = $('form'); var trans = new Array(); var parameters = { TransIDs: $("#TransID").val(), ItemIDs: $("#ItemID").val(), TypeIDs: $("#TypeID").val(), }; trans.push(parameters); if ($form.valid()) { $.ajax( { url: $form.attr('action'), type: $form.attr('method'), data: JSON.stringify(parameters), dataType: "json", contentType: "application/json; charset=utf-8", success: function (result) { $('#result').text(result.redirectTo) if (result.Success == true) { return fase; } else { $('#Error').html(result.Html); } }, error: function (request) { alert(request.statusText) } }); } e.preventDefault(); return false; }); }); This is my view code: <table> <tr> <th>trans</th> <th>Item</th> <th>Type</th> </tr> @foreach (var t in Model.Types.ToList()) { { <tr> <td> <input type="hidden" value="@t.TransID" id="TransID" /> <input type="hidden" value="@t.ItemID" id="ItemID" /> <input type="hidden" value="@t.TypeID" id="TypeID" /> </td> </tr> } } </table> This is the controller im trying to receive the data to: [HttpPost] public ActionResult Update(CustomTypeModel ctm) { return RedirectToAction("Index"); } What am i doing wrong?

    Read the article

  • A generic error has occurred in GDI+

    - by sysigy
    I know this has been asked a million times but I think I need to make it a million and one. I am getting "A generic error has occurred in GDI+" when trying to save a new bitmap. I have completely stripped down to the most basic lines of code and I still get the error with the following method: public class HomeController : Controller { public ActionResult Index() { return this.View(); } public void CreatePicture() { try { // THIS WORKS System.IO.File.Copy("C:\\copyTest.bmp", "C:\\test folder\\copyTest2.bmp"); // THIS WORKS System.IO.File.Delete("C:\\test folder\\deleteTest.bmp"); using (Bitmap newBitmap = new Bitmap(120, 120)) { // THIS FAILS newBitmap.Save("C:\\test folder\\test.bmp", ImageFormat.Bmp); } } catch (Exception ex) { throw ex; } } } The code is called from an html link on a blank page within an MVC 3.0 website using anonymous login. View: @Html.ActionLink("Create Picture", "CreatePicture", "Home", new { }) I have checked the folder permissions of "test folder" and have given full access to the following: ASPNET NETWORK SERVICE IUSR I still get the error... what have I missed / done wrong ?

    Read the article

  • ThickBox - update inside without redirect

    - by Alex Maslakov
    ASP.NET MVC and jQuery ThickBox. I show some content in ThickBox. It includes file upload form The view multi-media.apsx (it's strange, the this editor doesn't allow start the line with "<" in the code) form action="/upload/multi-media" method="post" enctype="multipart/form-data" label for="file"File name: input type="file" name="file" id="file" / input type="submit" value="Upload" / <% if (Model.Count > 0) { foreach (FileInfo mediaFile in Model) { <img width="100px" height="100px" src="<%: ResolveUrl("~/audio.png") %>" border="0" alt="<%: mediaFile.Name %>" / //................ After file upload I redirect to /upload/multi-media action and content shows in normal window, not in ThickBox. [ActionName("multi-media"), HttpPost] public ActionResult MultiMedia(HttpPostedFileBase file) { if (file.ContentLength > 0) { file.SaveAs(GenerateNewFileName(fullFileName)); return View("multi-media", model); } } How can I stay into ThickBox after file upload? I need show content in ThickBox all the time, even after the file upload.

    Read the article

  • Beginner MVC question - Correct approach to render out a List and details?

    - by fizzer
    I'm trying to set up a page where I display a list of items and the details of the selected item. I have it working but wonder whether I have followed the correct approach. I'll use customers as an example I have set the aspx page to inherit from an IEnumerable of Customers. This seems to be the standard approach to display the list of items. For the Details I have added a Customer user control which inherits from customer. I think i'm on the right track so far but I was a bit confused as to where I should store the id of the customer whose details I intend to display. I wanted to make the id optional in the controller action so that the page could be hit using "/customers" or "customers/1" so I made the arg optional and stored the id in the ViewData like this: public ActionResult Customers(string id = "0") { Models.DBContext db = new Models.DBContext(); var cList = db.Customers.OrderByDescending(c => c.CustomerNumber); if (id == "0") { ViewData["CustomerNumber"] = cList.First().CustomerNumber.ToString(); } else { ViewData["CustomerNumber"] = id; } return View("Customers", cList); } I then rendered the User control using RenderPartial in the front end: <%var CustomerList = from x in Model where x.CustomerNumber == Convert.ToInt32(ViewData["CustomerNumber"]) select x; Customer c = (Customer)CustomerList.First(); %> <% Html.RenderPartial("Customer",c); %> Then I just have an actionLink on each listed item: <%: Html.ActionLink("Select", "Customers", new { id = item.CustomerNumber })% It all seems to work but as MVC is new to me I would just be interested in others thoughts on whether this is a good approach?

    Read the article

  • Asynchronous Controller is blocking requests in ASP.NET MVC through jQuery

    - by Jason
    I have just started using the AsyncController in my project to take care of some long-running reports. Seemed ideal at the time since I could kick off the report and then perform a few other actions while waiting for it to come back and populate elements on the screen. My controller looks a bit like this. I tried to use a thread to perform the long task which I'd hoped would free up the controller to take more requests: public class ReportsController : AsyncController { public void LongRunningActionAsync() { AsyncManager.OutstandingOperations.Increment(); var newThread = new Thread(LongTask); newThread.Start(); } private void LongTask() { // Do something that takes a really long time //....... AsyncManager.OutstandingOperations.Decrement(); } public ActionResult LongRunningActionCompleted(string message) { // Set some data up on the view or something... return View(); } public JsonResult AnotherControllerAction() { // Do a quick task... return Json("..."); } } But what I am finding is that when I call LongRunningAction using the jQuery ajax request, any further requests I make after that back up behind it and are not processed until LongRunningAction completes. For example, call LongRunningAction which takes 10 seconds and then call AnotherControllerAction which is less than a second. AnotherControllerAction simply waits until LongRunningAction completes before returning a result. I've also checked the jQuery code, but this still happens if I specifically set "async: true": $.ajax({ async: true, type: "POST", url: "/Reports.aspx/LongRunningAction", dataType: "html", success: function(data, textStatus, XMLHttpRequest) { // ... }, error: function(XMLHttpRequest, textStatus, errorThrown) { // ... } }); At the moment I just have to assume that I'm using it incorrectly, but I'm hoping one of you guys can clear my mental block!

    Read the article

  • How can I post an array of string to ASP.NET MVC Controller without a form?

    - by rodbv
    Hi there, I am creating a small app to teach myself ASP.NET MVC and JQuery, and one of the pages is a list of items in which some can be selected. Then I would like to press a button and send a List (or something equivalent) to my controller containing the ids of the items that were selected, using JQuery's Post function. I managed to get an array with the ids of the elements that were selected, and now I want to post that. One way I could do this is to have a dummy form in my page, with a hidden value, and then set the hidden value with the selected items, and post that form; this looks crufty, though. Is there a cleaner way to achieve this, by sending the array directly to the controller? I've tried a few different things but it looks like the controller can't map the data it's receiving. Here's the code so far: function generateList(selectedValues) { var s = { values: selectedValues //selectedValues is an array of string }; $.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json"); } And then my Controller looks like this public ActionResult GenerateList(List<string> values) { //do something } All I managed to get is a "null" in the controller parameter... Any tips?

    Read the article

  • NUll exception in filling a querystring by mocing framework

    - by user564101
    There is a simple controller that a querystring is read in constructor of it. public class ProductController : Controller { parivate string productName; public ProductController() { productName = Request.QueryString["productname"]; } public ActionResult Index() { ViewData["Message"] = productName; return View(); } } Also I have a function in unit test that create an instance of this Controller and I fill the querystring by a Mock object like below. [TestClass] public class ProductControllerTest { [TestMethod] public void test() { // Arrange var querystring = new System.Collections.Specialized.NameValueCollection { { "productname", "sampleproduct"} }; var mock = new Mock<ControllerContext>(); mock.SetupGet(p => p.HttpContext.Request.QueryString).Returns(querystring); var controller = new ProductController(); controller.ControllerContext = mock.Object; // Act var result = controller.Index() as ViewResult; // Assert Assert.AreEqual("Index", result.ViewName); } } Unfortunately Request.QueryString["productname"] is null in constructor of ProductController when I run test unit. Is ther any way to fill a querystrin by a mocking and get it in constructor of a control?

    Read the article

  • Project Naming Convention Feedback Please

    - by Sam Striano
    I am creating a ASP.NET MVC 3 application using Entity Framework 4. I am using the Repository/Service Pattern and was looking for feedback. I currently have the following: MVC Application (GTG.dll) GTG GTG.Controllers GTG.ViewModels Business POCO's (GTG.Business.dll) This contains all business objects (Customer, Order, Invoice, etc...) EF Model/Repositories (GTG.Data.dll) GTG.Business (GTG.Context.tt) I used the Entity POCO Generator Templates. GTG.Data.Repositories Service Layer (GTG.Data.Services.dll) GTG.Data.Services - Contains all of the service objects, one per aggregate root. The following is a little sample code: Controller Namespace Controllers Public Class HomeController Inherits System.Web.Mvc.Controller Function Index() As ActionResult Return View(New Models.HomeViewModel) End Function End Class End Namespace Model Namespace Models Public Class HomeViewModel Private _Service As CustomerService Public Property Customers As List(Of Customer) Public Sub New() _Service = New CustomerService _Customers = _Service.GetCustomersByBusinessName("Striano") End Sub End Class End Namespace Service Public Class CustomerService Private _Repository As ICustomerRepository Public Sub New() _Repository = New CustomerRepository End Sub Function GetCustomerByID(ByVal ID As Integer) As Customer Return _Repository.GetByID(ID) End Function Function GetCustomersByBusinessName(ByVal Name As String) As List(Of Customer) Return _Repository.Query(Function(x) x.CompanyName.StartsWith(Name)).ToList End Function End Class Repository Namespace Data.Repositories Public Class CustomerRepository Implements ICustomerRepository Public Sub Add(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Add End Sub Public Sub Delete(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Delete End Sub Public Function GetByID(ByVal ID As Integer) As Business.Customer Implements IRepository(Of Business.Customer).GetByID Using db As New GTGContainer Return db.Customers.FirstOrDefault(Function(x) x.ID = ID) End Using End Function Public Function Query(ByVal Predicate As System.Linq.Expressions.Expression(Of System.Func(Of Business.Customer, Boolean))) As System.Linq.IQueryable(Of Business.Customer) Implements IRepository(Of Business.Customer).Query Using db As New GTGContainer Return db.Customers.Where(Predicate) End Using End Function Public Sub Save(ByVal Entity As Business.Customer) Implements IRepository(Of Business.Customer).Save End Sub End Class End Namespace

    Read the article

  • Login fails when recreating database with Code First

    - by Mun
    I'm using ASP.NET Entity Framework's Code First to create my database from the model, and the login seems to fail when the database needs to be recreated after the model changes. In Global.asax, I've got the following: protected void Application_Start() { Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EntriesContext>()); // ... } In my controller, I've got the following: public ActionResult Index() { // This is just to force the database to be created var context = new EntriesContext(); var all = (from e in context.Entries select e).ToList(); } When the database doesn't exist, it is created with no problems. However, when I make a change to the model, rebuild and refresh, I get the following error: Login failed for user 'sa'. My connection string looks like this: <add name="EntriesContext" connectionString="Server=(LOCAL);Database=MyDB;User Id=sa;Password=password" providerName="System.Data.SqlClient" /> The login definitely works as I can connect to the server and the database from Management Studio using these credentials. If I delete the database manually, everything works correctly and the database is recreated as expected with the schema reflecting the changes made to the model. It seems like either the password or access to the database is being lost. Is there something else I need to do to get this working?

    Read the article

  • integrating jquery with AJAX using MVC for ddl/html.dropdownlist

    - by needhelp
    the situation: a user on the page in question selects a category from a dropdown which then dynamically populates all the users of that category in a second dropdown beside it. all the data is being retrieved using LinqtoSQL and i was wondering if this can be done a) using html.dropdownlist in a strongly typed view? b) using jquery to trigger the ajax request on selected index change instead of a 'populate' button trigger? sorry i dont have code as what i was trying really wasnt working at all. I am having trouble with how to do it conceptually and programatically! will appreciate any links to examples etc greatly! thanks in advance! EDIT: this is kind of what i was trying to achieve.. first the ViewPage: <script type="text/javascript"> $(document).ready function TypeSearch() { $.getJSON("/Home/Type", null, function(data) { //dont know what to do here }); } </script> <p> <label for="userType">userType:</label> <%= Html.DropDownList("userType") %> <%= Html.ValidationMessage("userType", "*") %> <input type="submit" runat="server" onclick="TypeSearch()" /> <label for="accountNumber">accountNumber:</label> <%= Html.DropDownList("accountNumber") %> <%= Html.ValidationMessage("accountNumber", "*") %> </p> Then home controller action: public ActionResult Type() { string accountType = dropdownvalue; List<Account> accounts = userRep.GetAccountsByType(accountType).ToList(); return Json(accounts); }

    Read the article

  • How to implement a search page which shows results on the same page?

    - by Andrew
    I'm using ASP.NET MVC 2 for the first time on a project at work and am feeling like a bit of a noob. I have a page with a customer search control/partial view. The control is a textbox and a button. You enter a customer id into the textbox and hit search. The page then "refreshes" and shows the customer details on the same page. In other words, the customer details appear below the customer search control. This is so that if the customer isn't the right one, the user can search again without hitting back in the browser. Or, perhaps they mistyped the customer id and need to try again. I want the URL to look like this: /Customer/Search/1 Obviously, this follows the default route in the project. Now, if I type the URL above directly into my browser, it works fine. However, when I then use the search control on that page to search for say customer 2, the page refreshes with the correct customer details but the URL does not change! It stays as /Customer/Search/1 When I want it to be /Customer/Search/2 How can I get it to change to the correct URL? I am only using the default route in Global.asax. My Search method looks like this: <AcceptVerbs(HttpVerbs.Get)> _ Function Search(ByVal id As String) As ActionResult Dim customer As Customer = New CustomerRepository().GetById(id) Return View("SearchResult", customer) End Function

    Read the article

  • a potentially dangerous request.form value was detected but validateinput(false) not working

    - by tonybolding
    I have installed VS2010 and MVC2 and testing a simple form using tinyMCE. When I post the contents of the textarea in tinyMCE I get the dreaded YSD and the message "a potentially dangerous....." No problem I thought - seen this before so I put the ValidateInput(false) on the controller but no joy - I still get the error. page code in edit.aspx is: <% using (Html.BeginForm()){ % <!-- Gets replaced with TinyMCE, remember HTML in a textarea should be encoded --> <textarea id="elm1" name="mceText" rows="15" cols="80" style="width: 80%"> &lt;p&gt; This is some example text that you can edit inside the &lt;strong&gt;TinyMCE editor&lt;/strong&gt;. </textarea> <br /> <input type="submit" name="save" value="Submit" /> <input type="reset" name="reset" value="Reset" /> <%} % and Controller action is: [AcceptVerbs(HttpVerbs.Post)] [ValidateInput(false)] public ActionResult Edit(string mceText) { return View(); } Any thoughts - (I know the code is not complete) been trying this for hours but everyone just says to use ValidateInput(false)

    Read the article

  • Pass 2-dimensional array trough view

    - by Mikael
    Hi, I'm trying to print a 2-dimensional array but can't figure it out. My controller uses this code: public ActionResult Test(string str) { DateTimeOffset offset = new DateTimeOffset(DateTime.Now); offset = offset.AddHours(-5); string[,] weekDays = new string[7,2]; for (int i = 0; i < 7; i++) { weekDays[i,0] = String.Format("{0:yyyy-MM-dd:dddd}", offset); //Date weekDays[i,1] = String.Format("{0:dddd}", offset); //Text offset = offset.AddHours(24); } weekDays[0,1] = "Today"; ViewData["weekDays"] = weekDays; return View(); } Now I wan't to print this array of weekdays as a dropdown-list and i thought this would work: <% foreach (var item in (string[,])ViewData["weekDays"]) { %> <option value=" <%= item[0] %> "> <%= item[1] %> </option> <% } %> But that's not the case, this code output just the first char of the string. So anyone got a suggestion? Thanks! /M

    Read the article

  • ASP.NET MVC Query Help

    - by Cameron
    I have the following Index method on my app that shows a bunch of articles: public ActionResult Index(String query) { var ArticleQuery = from m in _db.ArticleSet select m; if (!string.IsNullOrEmpty(query)) { ArticleQuery = ArticleQuery.Where(m => m.headline.Contains(query)); } //ArticleQuery = ArticleQuery.OrderBy(m.posted descending); return View(ArticleQuery.ToList()); } It also doubles as a search mechanism by grabbing a query string if it exists. Problem 1.) The OrderBy does not work, what do I need to change it to get it to show the results by posted date in descending order. Problem 2.) I am going to adding a VERY SIMPLE pagination, and therefore only want to show 4 results per page. How would I be best going about this? Thanks EDIT: In addition to problem 2, I'm looking for a simple Helper class solution to implement said pagination into my current code. This ones looks very good (http://weblogs.asp.net/andrewrea/archive/2008/07/01/asp-net-mvc-quot-pager-quot-html-helper.aspx), but how would I implement it into my application. Thanks.

    Read the article

  • Replacing one image with another image through ajax makes it dissappear for a split second

    - by ooo
    I have the following code (asp.net-mvc, jquery) (i have simplified the example to show the issue) where i want to click on an image and have it replaced with another image. This works fine but the first time i click it, the original image disappears (for a split second) before the other image shows up. After that it works seamlessly. Is there any way to eliminate this quirk so there is not split second where no image is shown? Here is my controller code: public ActionResult UpdateFavoriteExercise(int id, string toggle) { if (toggle == "off") { return Content("<img toggle='off' src='/images/vote-favorite-off1.png' border=0'>"); } return Content("<img toggle='on' src='/images/vote-favorite-on1.png' border=0'>"); } Here is my jquery code: $('div.favoriteExercise').live('click', function() { var id = $(this).attr("id"); var toggle = $(this).attr("toggle"); if (toggle == 'off') { onOff = 'on'; } else { onOff = 'off'; } var url = '/Tracker/UpdateFavoriteExercise/' + id + '?toggle=' + onOff; $(this).load(url); $(this).attr("toggle", onOff); });

    Read the article

  • How to make paging start from 1 instead of 0 in ASP.NET MVC

    - by ssx
    I used the paging example of the Nerddinner tutorial. But I also wanted to add page Numbers, somehting like that: <<< 1 2 3 4 5 6 The code below works if i start my paging from 0, but not from 1. How can I fix this ? Here is my code: PaginatedList.cs public class PaginatedList<T> : List<T> { public int PageIndex { get; private set; } public int PageSize { get; private set; } public int TotalCount { get; private set; } public int TotalPages { get; private set; } public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize) { PageIndex = pageIndex; PageSize = pageSize; TotalCount = source.Count(); TotalPages = (int) Math.Ceiling(TotalCount / (double)PageSize); this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize)); } public bool HasPreviousPage { get { return (PageIndex > 0); } } public bool HasNextPage { get { return (PageIndex+1 < TotalPages); } } } UserController.cs public ActionResult List(int? page) { const int pageSize = 20; IUserRepository userRepository = new UserRepository(); IQueryable<User> listUsers = userRepository.GetAll(); PaginatedList<User> paginatedUsers = new PaginatedList<User>(listUsers, page ?? 0, pageSize); return View(paginatedUsers); } List.cshtml @if (Model.HasPreviousPage) { @Html.RouteLink(" Previous ", "PaginatedUsers", new { page = (Model.PageIndex - 1) }) } @for (int i = 1; i <= Model.TotalPages; i++) { @Html.RouteLink(@i.ToString(), "PaginatedUsers", new { page = (@i ) }) } @if (Model.HasNextPage) { @Html.RouteLink(" Next ", "PaginatedUsers", new { page = (Model.PageIndex + 1) }) }

    Read the article

< Previous Page | 28 29 30 31 32 33 34 35 36 37 38  | Next Page >