Search Results

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

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

  • how to return an error in an Ajax scenario from ASP.NET MVC action

    - by mohang
    I am using ASP.NET MVC with jquery. I have the following MVC Action that returns a partial page on Success. On Application Error, I am not sure what to send it for correctly handling it at the client side. public ActionResult LoadFilterSet(int filterSetId) { try { BreadCrumbManager bcManager = this.ResetBreadCrumbManager(this.BreadCrumbManagerID); GeneralHelper.LoadBreadCrumbManager(bcManager, filterSetId); ViewData["BreadCrumbManager"] = bcManager; return View("LoadFilterSet"); } catch (Exception ex) { return Content(""); } } Following is my jquery ajax call. Notice that I am checking for the data length to make sure there are no errors. Please suggest me a better way of doing this. $.ajax({ type: "GET", dataType: "html", async: true, data: ({ filterSetId: selectedId }), url: link, contentType: "text/html; charset=utf-8", success: function(data, textStatus) { if (data.length > 0) { // Clear the local filters first. clearLocalFilters(); $('td.selected-filters table.filters-display').append(data); } } });

    Read the article

  • Pass a model object while using a upload

    - by Dejan.S
    I'm trying to pass my model object along with the file I'm uploading but I'm stuck on how I should that should be done. This is the code I use now [AcceptVerbs(HttpVerbs.Post)] public ActionResult Upload(PageBody pageBody) { foreach (string file in Request.Files) { var hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0) continue; string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Content/Uploads/", Path.GetFileName(hpf.FileName)); hpf.SaveAs(savedFileName); _pageBody.Pictures.Add(new PageBodyPicture() { Picture = file }); } return View(pageBody); } here is my view code, I got the model.Id but there but it wont pass even if I put just Id to the Upload method. <form action="/Admin/Upload" enctype="multipart/form-data" method="post"> <%= Html.HiddenFor(model => model.Id)%> <input type="file" name="file" id="file" /><br /> <input type="submit" name="submit" value="Upload" /> </form>

    Read the article

  • List of Users and Role using Membership Provider

    - by Jemes
    I’m trying to produce a view to show a list of users and their role using the built in membership provider. My model and controller are picking up the users and roles but I’m having trouble displaying them in my view. Model public class AdminViewModel { public MembershipUserCollection Users { get; set; } public string[] Roles { get; set; } } Controller public ActionResult Admin() { AdminViewModel viewModel = new AdminViewModel { Users = MembershipService.GetAllUsers(), Roles = RoleService.GetRoles() }; return View(viewModel); } View Inherits="System.Web.Mvc.ViewPage<IEnumerable<Account.Models.AdminViewModel>>" <table> <tr> <td>UserName</td> <td>Email</td> <td>IsOnline</td> <td>CreationDate</td> <td>LastLoginDate</td> <td>LastActivityDate</td> </tr> <% foreach (var item in Model) { %> <tr> <td><%=item.UserName %></td> <td><%=item.Email %></td> <td><%=item.IsOnline %></td> <td><%=item.CreationDate %></td> <td><%=item.LastLoginDate %></td> <td><%=item.LastActivityDate %></td> <td><%=item.ROLE %></td> </tr> <% }%> </table>

    Read the article

  • Web API Getting Http 500 error : Issue Solved See Below

    - by Joe Grasso
    Here is my MVC Controller and everything is fine: private UnitOfWork UOW; public InventoryController() { UOW = new UnitOfWork(); } // GET: /Inventory/ public ActionResult Index() { var products = UOW.ProductRepository.GetAll().ToList(); return View(products); } Same method call in API Controller gives me an Http 500 Error: private UnitOfWork _unitOfWork; public TestController() { _unitOfWork = new UnitOfWork(); } public IEnumerable<Product> Get() { var products = _unitOfWork.ProductRepository.GetAll().ToList(); return products; } Debugging shows that indeed there is data being returned in both controllers' UOW calls. I then added a customer configuration in Global: public static void CustomizeConfig(HttpConfiguration config) { config.Formatters.Remove(config.Formatters.XmlFormatter); var json = config.Formatters.JsonFormatter; json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } I am still receiving an Http 500 in API Controller ONLY and at a loss as to why. Any ideas? UPDATE: It appears using lazy loading caused the problem. When I set the associated properties to NON-VIRTUAL the Test API provided the necessary JSON string. However, whereas before I had the Vendor class included, I only have VendorId. I really wanted to included the associated classes. Any ideas? I know there are alot of smart people out there. Anyone?

    Read the article

  • ASP.NET MVC Unit Testing Controllers - Repositories

    - by Brian McCord
    This is more of an opinion seeking question, so there may not be a "right" answer, but I would welcome arguments as to why your answer is the "right" one. Given an MVC application that is using Entity Framework for the persistence engine, a repository layer, a service layer that basically defers to the repository, and a delete method on a controller that looks like this: public ActionResult Delete(State model) { try { if( model == null ) { return View( model ); } _stateService.Delete( model ); return RedirectToAction("Index"); } catch { return View( model ); } } I am looking for the proper way to Unit Test this. Currently, I have a fake repository that gets used in the service, and my unit test looks like this: [TestMethod] public void Delete_Post_Passes_With_State_4() { //Arrange var stateService = GetService(); var stateController = new StateController( stateService ); ViewResult result = stateController.Delete( 4 ) as ViewResult; var model = (State)result.ViewData.Model; //Act RedirectToRouteResult redirectResult = stateController.Delete( model ) as RedirectToRouteResult; stateController = new StateController( stateService ); var newresult = stateController.Delete( 4 ) as ViewResult; var newmodel = (State)newresult.ViewData.Model; //Assert Assert.AreEqual( redirectResult.RouteValues["action"], "Index" ); Assert.IsNull( newmodel ); } Is this overkill? Do I need to check to see if the record actually got deleted (as I already have Service and Repository tests that verify this)? Should I even use a fake repository here or would it make more sense just to mock the whole thing? The examples I'm looking at used this model of doing things, and I just copied it, but I'm really open to doing things in a "best practices" way. Thanks.

    Read the article

  • asp.net mvc 2 - return JavaScript with View

    - by Tomaszewski
    Hi, using ASP.NET MVC 2 I have a navigation menu inside my Master Page. In the navigation menu, I am trying add a class to the that the current page relates to (i.e., home page will add class="active" to the Home button). I'm trying to consider scalability and the fact that I don't want to change individual pages if the navigation changes later. The only way I can think of doing this is: Add JavaScript to each individual View that will add the class when the DOM is ready Return JavaScript when return View() occurs on point (2), I am unsure how to do. Thusfar I have been doing the following in my controller: public ActionResult Index() { ViewData["messege"] = JavaScript("<script type='text/javascript' language='javascript'> $(document).ready(function () { console.log('hi hi hi'); }); </script>"); return View(); } but in my view, when I call: <%: ViewData["messege"] %> I get: System.Web.Mvc.JavaScriptResult as the result Would you guys have any ideas on How to solve the navigation menu probelem, other than the solutions I've listed return JavaScript along with your view from the Controller Thanks, in advanced!

    Read the article

  • ASP.NET MVC (VB) error when publishing to test server

    - by Colin
    I have an ASP.NET MVC project that works fine on my local machine (no build errors, server errors or anything). However, when I publish the project to a test server, I get an "Object reference not set to an instance of an object" error on a For Each I have in my view. I have a function within a model that returns a DataRowCollection. I'm calling that function in my controller and passing the DataRowCollection to my View, which then iterates over the rows and displays the necessary information: In the Controller I have: Function Index() As ActionResult Dim MyModel As New Model ViewData("MyDataRowCollection") = MyModel.GetDataRowCollection() Return View() End Function And then in the View, which is throwing the error: <%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server"> My Page Title </asp:Content> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <% For Each MyDataRow In ViewData("MyDataRowCollection") ' do stuff with each MyDataRow Next %> I'm pretty new to ASP.NET MVC so I'm sure there might be a better way to do what I'm doing (I'd be happy to hear if there is), but my main concern is why this works fine on my local machine but throws an error on the For Each on the test server? Please let me know if I can clarify any of the above, and thanks in advance for any information.

    Read the article

  • MVC2 Json request not actually hitting the controller

    - by SlackerCoder
    I have a JSON request, but it seems that it is not hitting the controller. Here's the jQuery code: $("#ddlAdminLogsSelectLog").change(function() { globalLogSelection = $("#ddlAdminLogsSelectLog").val(); alert(globalLogSelection); $.getJSON("/Administrative/AdminLogsChangeLogSelection", { NewSelection: globalLogSelection }, function(data) { if (data.Message == "Success") { globalCurrentPage = 1; } else if (data.Message == "Error") { //Do Something } }); }); The alert is there to show me if it actually fired the change event, which it does. Heres the method in the controller: public ActionResult AdminLogsChangeLogSelection(String NewSelection) { String sMessage = String.Empty; StringBuilder sbDataReturn = new StringBuilder(); try { if (NewSelection.Equals("Application Log")) { int i = 0; } else if (NewSelection.Equals("Email Log")) { int l = 0; } } catch (Exception e) { //Do Something sMessage = "Error"; } return Json(new { Message = sMessage, DataReturn = sbDataReturn.ToString() }, JsonRequestBehavior.AllowGet); } I have a bunch of Json requests in my application, and it seems to only happen in this area. This is a separate area (I have 6 "areas" in the app, 5 of which work fine with JSON requests). This controller is named "AdministrativeController", if that matters. Does anything jump out anyone as being incorrect or why the request would not pass to the server side?

    Read the article

  • ASP.NET MVC 2 - Custom route doesn't find controller action

    - by mcfroob
    For some reason my application isn't routing to my controller method correctly. I have a routelink like this in my webpage - <%= Html.RouteLink("View", "Blog", new { id=(item.BlogId), slug=(item.Slug) }) %> In global.asax.cs I have the following routes - routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "MoreBlogs", "Blog/Page/{page}", new { controller = "Blog", action = "Index" } ); routes.MapRoute( "Blog", "Blog/View/{id}/{slug}", new { controller = "Blog", action = "View"} ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Blog", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); And then I have a class BlogController that has a method - public ActionResult View(int id, string slug) { ... etc. } I put a breakpoint in the first line of the View method but it's not getting hit at all. I checked with a route debugger for the format localhost/Blog/View/1/test and it matched my custom route. All I'm getting is a 404 while running this, I can't work out why the route won't post to the view method in my controller - any ideas?

    Read the article

  • ASP.NET MVC Dropdownlist retain the selected value in the browser after post

    - by MLabib
    I build a drop down list in my aspx page as following <%= Html.DropDownList("SelectedRole", new SelectList((IEnumerable)Model.roles, "RoleId", "RoleName", Model.SelectedRole), "")%> it works fine for first Get and the first default value is selected; then I select item from the drop down list and submit the form. the controller bind the values correctly, public ActionResult About([Bind] Roles r) { //r.SelectedRole = the selected value in the page. //Roles r = new Roles(); r.roles = new List<Role>(); r.roles.Add(new Role(1, "one")); r.roles.Add(new Role(2, "two")); r.roles.Add(new Role(3, "three")); r.roles.Add(new Role(4, "four")); r.SelectedRole = null; return View(r) } Then I nullify the selected item and return my view, but still the previous selected Item is selected (although I did nullify it) Any Idea if I am doing something wrong or it is a bug in MVC? I am using ASP.NET MVC 1 Thanks

    Read the article

  • Updating database row from model

    - by Jamie Dixon
    Hey everyone, I'm haing a few problems updating a row in my database using Linq2Sql. Inside of my model I have two methods for updating and saving from my controller, which in turn receives an updated model from my view. My model methods like like: public void Update(Activity activity) { _db.Activities.InsertOnSubmit(activity); } public void Save() { _db.SubmitChanges(); } and the code in my Controller likes like: [HttpPost] public ActionResult Edit(Activity activity) { if (ModelState.IsValid) { UpdateModel<Activity>(activity); _activitiesModel.Update(activity); _activitiesModel.Save(); } return View(activity); } The problem I'm having is that this code inserts a new entry into the database, even though the model item i'm inserting-on-submit contains a primary key field. I've also tried re-attaching the model object back to the data source but this throws an error because the item already exists. Any pointers in the right direction will be greatly appreciated. UPDATE: I'm using dependancy injection to instantiate my datacontext object as follows: IMyDataContext _db; public ActivitiesModel(IMyDataContext db) { _db = db; }

    Read the article

  • what is the best way to optimize my json on an asp.net-mvc site

    - by ooo
    i am currently using jqgrid on an asp.net mvc site and we have a pretty slow network (internal application) and it seems to be taking the grid a long time to load (the issue is both network as well as parsing, rendering) I am trying to determine how to minimized what i send over to the client to make it as fast as possible. Here is a simplified view of my controller action to load data into the grid: [AcceptVerbs(HttpVerbs.Get)] public ActionResult GridData1(GridData args) { var paginatedData = applications.GridPaginate(args.page ?? 1, args.rows ?? 10, i => new { i.Id, Name = "<div class='showDescription' id= '" + i.id+ "'>" + i.Name + "</div>", MyValue = GetImageUrl(_map, i.value, "star"), ExternalId = string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", Url.Action("Link", "Order", new { id = i.id }), i.Id), i.Target, i.Owner, EndDate = i.EndDate, Updated = "<div class='showView' aitId= '" + i.AitId + "'>" + GetImage(i.EndDateColumn, "star") + "</div>", }) return Json(paginatedData); } So i am building up a json data (i have about 200 records of the above) and sending it back to the GUI to put in the jqgrid. The one thing i can thihk of is Repeated data. In some of the json fields i am appending HTML on top of the raw "data". This is the same HTML on every record. It seems like it would be more efficient if i could just send the data and "append" the HTML around it on the client side. Is this possible? Then i would just be sending the actual data over the wire and have the client side add on the rest of the HTML tags (the divs, etc) be put together. Also, if there are any other suggestions on how i can minimize the size of my messages, that would be great. I guess at some point these solution will increase the client side load but it may be worth it to cut down on network traffic.

    Read the article

  • jQuery preventing RedirectToAction from working?

    - by DaveDev
    I'm trying to redirect the user if they login successfully but the code I have on my page seems to be preventing the redirection from working. If I remove the jQuery below the redirection works. Can somebody tell me tell me if there's something I'm doing wrong? Thanks I have the following Action: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Login(User user) { var myErrors = new Dictionary<string, string>(); try { if (ModelState.IsValid) { if (userRepository.ValidUser(user)) { return RedirectToAction("Index", "Group", new {page = (int?)null}); } else { return Json("Username or password seems to be incorrect"); } } else { foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState) { if (keyValuePair.Value.Errors.Count > 0) { List<string> errors = new List<string>(); myErrors.Add(keyValuePair.Key, keyValuePair.Value.Errors[0].ErrorMessage); } } return Json(myErrors); } } catch (Exception) { return Json("Invalid"); } } and the following code on my page: <script language="javascript" type="text/javascript"> $(document).ready(function() { $("#SaveSuccess").hide(); $("#btnLogin").click(function() { $("form").submit(function(event) { var formData = $(this).serialize(); $.post($(this).attr("action"), formData, function(res) { ShowErrors(res); if (res == true) { $("#SaveSuccess").text("Saved"); } else { $("#divError").html(res); } $("#SaveSuccess").fadeIn(100); }, "json"); return false; }); }); }); </script>

    Read the article

  • Discusses some issues related to mvc2.0

    - by hao123
    ???????????????,???????? ??: ???????:1????????2????????3???? ?????????????? ??????:1???????:http://demo.com/admin/News/index 2???????:http://demo.com/s7mmer/News/index 3?????:http://demo.com/News/index ??asp.net mvc1.0???????????,?????,??asp.net mvc2.0???Areas?? ??: ???????,?????????????Admin?areas,??VS?????????????areas????,????????????????? ??????????: 1?????????Areas???? 2??Areas ???????? 3?????,?Areas?????????MyAreaRegistration.cs ????: ?? using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace S7mmer.Web { public class AdminAreaRegistration : AreaRegistration { public override string AreaName { get { return "Admin"; } } public override void RegisterArea(AreaRegistrationContext context) { //?????????? context.MapRoute( "AdminController_default", "Admin/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new string[] { "S7mmer.Web.Areas.Admin.Controllers" }//controllers????? ); } } public class S7mmerAreaRegistration : AreaRegistration { public override string AreaName { get { return "S7mmer"; } } public override void RegisterArea(AreaRegistrationContext context) { //?????????? context.MapRoute( "S7mmerController_default", "S7mmer/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new string[] { "S7mmer.Web.Areas.S7mmer.Controllers" }//controllers????? ); } } public class WebSiteAreaRegistration : AreaRegistration { public override string AreaName { get { return "WebSite"; } } public override void RegisterArea(AreaRegistrationContext context) { //?????????? context.MapRoute( "WebSiteController_default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }, // Parameter defaults new string[] { "S7mmer.Web.Areas.WebSite.Controllers" }//controllers????? ); } } } 4??Areas?????Admin????????NewsController.cs 5??NewsController.cs??public ActionResult Index()?????view,??? ???news????index.aspx 6????????Global.asax??,?Application_Start()????AreaRegistration.RegisterAllAreas(); protected void Application_Start() { AreaRegistration.RegisterAllAreas(); // RegisterRoutes(RouteTable.Routes); } ????? http://localhost:1108/admin/News/index,??????????! ??????????????????,???????????????,????

    Read the article

  • Detect whether or not a specific attribute was valid on the model

    - by Sir Code-A-Lot
    Having created my own validation attribute deriving from System.ComponentModel.DataAnnotations.ValidationAttribute, I wish to be able to detect from my controller, whether or not that specific attribute was valid on the model. My setup: public class MyModel { [Required] [CustomValidation] [SomeOtherValidation] public string SomeProperty { get; set; } } public class CustomValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { // Custom validation logic here } } Now, how do I detect from the controller whether validation of CustomValidationAttribute succeeded or not? I have been looking at the Exception property of ModelError in the ModelState, but I have no way of adding a custom exception to it from my CustomValidationAttribute. Right now I have resorted to checking for a specific error message in the ModelState: public ActionResult PostModel(MyModel model) { if(ModelState.Where(i => i.Value.Errors.Where((e => e.ErrorMessage == CustomValidationAttribute.SharedMessage)).Any()).Any()) DoSomeCustomStuff(); // The rest of the action here } And changed my CustomValidationAttribute to: public class CustomValidationAttribute : ValidationAttribute { public static string SharedMessage = "CustomValidationAttribute error"; public override bool IsValid(object value) { ErrorMessage = SharedMessage; // Custom validation logic here } } I don't like relying on string matching, and this way the ErrorMessage property is kind of misused. What are my options?

    Read the article

  • ASP.MVC 2 Model Data Persistance

    - by toccig
    I'm and MVC1 programmer, new to the MVC2. The data will not persist to the database in an edit scenario. Create works fine. Controller: // // POST: /Attendee/Edit/5 [Authorize(Roles = "Admin")] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Attendee attendee) { if (ModelState.IsValid) { UpdateModel(attendee, "Attendee"); repository.Save(); return RedirectToAction("Details", attendee); } else { return View(attendee); } } Model: [MetadataType(typeof(Attendee_Validation))] public partial class Attendee { } public class Attendee_Validation { [HiddenInput(DisplayValue = false)] public int attendee_id { get; set; } [HiddenInput(DisplayValue = false)] public int attendee_pin { get; set; } [Required(ErrorMessage = "* required")] [StringLength(50, ErrorMessage = "* Must be under 50 characters")] public string attendee_fname { get; set; } [StringLength(50, ErrorMessage = "* Must be under 50 characters")] public string attendee_mname { get; set; } } I tried to add [Bind(Exclude="attendee_id")] above the Class declaration, but then the value of the attendee_id attribute is set to '0'. View (Strongly-Typed): <% using (Html.BeginForm()) {%> ... <%=Html.Hidden("attendee_id", Model.attendee_id) %> ... <%=Html.SubmitButton("btnSubmit", "Save") %> <% } %> Basically, the repository.Save(); function seems to do nothing. I imagine it has something to do with a primary key constraint violation. But I'm not getting any errors from SQL Server. The application appears to runs fine, but the data is never persisted to the Database.

    Read the article

  • Random number generation in MVC applications

    - by SlimShaggy
    What is the correct way of generating random numbers in an ASP.NET MVC application if I need exactly one number per request? According to MSDN, in order to get randomness of sufficient quality, it is necessary to generate multiple numbers using a single System.Random object, created once. Since a new instance of a controller class is created for each request in MVC, I cannot use a private field initialized in the controller's constructor for the Random object. So in what part of the MVC app should I create and store the Random object? Currently I store it in a static field of the controller class and lazily initialize it in the action method that uses it: public class HomeController : Controller { ... private static Random random; ... public ActionResult Download() { ... if (random == null) random = new Random(); ... } } Since the "random" field can be accessed by multiple instances of the controller class, is it possible for its value to become corrupted if two instances attempt to initialize it simultaneously? And one more question: I know that the lifetime of statics is the lifetime of the application, but in case of an MVC app what is it? Is it from IIS startup till IIS shutdown?

    Read the article

  • What does this model error says in asp.net mvc?

    - by Pandiya Chendur
    My Html action link takes me to a view where i can see the details.. For Ex:http://localhost:1985/Materials/Details/4 But it shows error, The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[CrMVC.Models.ConstructionRepository+Materials]' but this dictionary requires a model item of type 'CrMVC.Models.ConstructionRepository+Materials'. And my model is... public IQueryable<Materials> GetMaterial(int id) { return from m in db.Materials join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id where m.Mat_id == id select new Materials() { Id = Convert.ToInt64(m.Mat_id), Mat_Name = m.Mat_Name, Mes_Name = Mt.Name, }; } public class Materials { private Int64 id; public string mat_Name; public string mes_Name; public Int64 Id { get { return id; } set { id = value; } } public string Mat_Name { get { return mat_Name; } set { mat_Name = value; } } public string Mes_Name { get { return mes_Name; } set { mes_Name = value; } } } } and my controller method... public ActionResult Details(int id) { var material = consRepository.GetMaterial(id).AsQueryable(); return View("Details", material); } Any suggestion what am i missing here?

    Read the article

  • Model binding difficulty

    - by user281180
    I am having a model and I am using ajax.post. I can see that the model binding isn`t being done for the arraylists in my model, though binding done for the properties of int or string type. Why is that so? My code is as below. I have a model with the following properties public class ProjectModel { public int ID { get; set; } public ArrayList Boys= new ArrayList(); } In my view I have $(document).ready(function () { var project = new Object(); var Boys= new Array(); var ID; ....... ID = $('#ID').val(); project.Boys= Boys; ..... $.ajax({ type: "POST", url: '<%=Url.Action("Create","Project") %>', data: JSON.stringify(project), contentType: "application/json; charset=utf-8", dataType: "html", success: function () { }, error: function (request, status, error) { } }); // My controller [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(ProjectModel project) { try { project.CreateProject(); return RedirectToAction("Index"); } ....

    Read the article

  • How does asp.net MVC remember my false values on postback?

    - by Michel
    Hi, This is working, but how??? I have a controller action for a post: [AcceptVerbs(HttpVerbs.Post )] public ActionResult Edit(Person person) { bool isvalid = ModelState.IsValid; etc. The Person object has a property BirthDate, type DateTime. When i enter some invalid data in the form, say 'blabla' which is obvious not a valid Datetime, it fills all the (other) Person properties with the correct data and the BirthDate property with a new blank DateTime. The bool isvalid has the value 'false'. So far so good. Then i do this: return View(p); and in the view i have this: <%= Html.TextBox("BirthDate", String.Format("{0:g}", Model.BirthDate)) %> <%= Html.ValidationMessage("BirthDate", "*") %> Ant there it comes: i EXPECTED the model to contain the new, blank DateTime because i didn't put any new data in. Second, when the View displays something, it must be a DateTime, because Model.BirthDate can't hold anything but a DateTime. But to my surprise, it shows a textbox with the 'blabla' value! (and the red * behind it) Which ofcourse is nice because the user can seee what he typed wrong, but how can that (blabla)string be transferred to the View in a DateTime field?

    Read the article

  • Error when trying to overwrite an image (it succeeds the first time after iis reset )

    - by Omu
    First time (after iis reset) I succeed to overwrite the image, but if I try again it gives me that GDI error this is my code: [HttpPost] public ActionResult Change() { var file = Request.Files["fileUpload"]; if (file.ContentLength > 0) { var filePath = @ConfigurationManager.AppSettings["storagePath"] + @"\Temp\" + User.Identity.Name + ".jpg"; using (var image = Image.FromStream(file.InputStream)) { var size = ResizeImage(image, filePath, 600, 480, true); return RedirectToAction("Crop", new CropDisplay {ImageWidth = size[0], ImageHeight = size[1]}); } } return RedirectToAction("Index"); } private int[] ResizeImage(Image image, string newFilePath, int newWidth, int maxHeight, bool onlyResizeIfWider) { ... using (var thumbnail = new Bitmap(newWidth, newHeight)) { using (var graphic = Graphics.FromImage(thumbnail)) { graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; graphic.DrawImage(image, 0, 0, newWidth, newHeight); var info = ImageCodecInfo.GetImageEncoders(); var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); //this is where I get the GDI error thumbnail.Save(newFilePath, info[1], encoderParameters); return new[] { newWidth, newHeight }; } } }

    Read the article

  • ASP.Net MVC TDD using Moq

    - by Nicholas Murray
    I am trying to learn TDD/BDD using NUnit and Moq. The design that I have been following passes a DataService class to my controller to provide access to repositories. I would like to Mock the DataService class to allow testing of the controllers. There are lots of examples of mocking a repository passed to the controller but I can't work out how to mock a DataService class in this scenerio. Could someone please explain how to implement this? Here's a sample of the relevant code: [Test] public void Can_View_A_Single_Page_Of_Lists() { var dataService = new Mock<DataService>(); var controller = new ListsController(dataService); ... } namespace Services { public class DataService { private readonly IKeyedRepository<int, FavList> FavListRepository; private readonly IUnitOfWork unitOfWork; public FavListService FavLists { get; private set; } public DataService(IKeyedRepository<int, FavList> FavListRepository, IUnitOfWork unitOfWork) { this.FavListRepository = FavListRepository; this.unitOfWork = unitOfWork; FavLists = new FavListService(FavListRepository); } public void Commit() { unitOfWork.Commit(); } } } namespace MyListsWebsite.Controllers { public class ListsController : Controller { private readonly DataService dataService; public ListsController(DataService dataService) { this.dataService = dataService; } public ActionResult Index() { var myLists = dataService.FavLists.All().ToList(); return View(myLists); } } }

    Read the article

  • Change HTML image into a Button for partial refresh of page

    - by user990951
    I am new to webpage design and MVC. I have a aspx page and I have a html image. I want to change this image and make it clickable so that it will refresh only the bottom half of the page when clicked. I setup my image so that the source of the image is updated by the controller. By using the following src="<%=ViewData["BookImg"] %>" So that the whole story is clear. When a person clicks on the image of the book, it displays on the bottom half of the page information about that book pulled from a sql database. I am thinking that I would need to look into getting ajax implemented so that I can do partial page update. But the question is how do I change that HTML image into a button. Thanks in advance. ---updating per the answer chosen but still having problems--- home.aspx <% Html.RenderPartial("HomePartialView"); %> <img id = "Book_Img" src="<%=ViewData["BookImg"] %>" alt = "click Me" class="imgClick"/> <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"> $(document).ready(function(){ $(".imgClick").click(function () { $("HomePartialView").load("../../Controllers/HomeController/PartialViewBook"); }); }); </script> ---Controller public ActionResult PartialViewBook() { ViewData[imageBookPressd] = "hello world"; return View("HomePartialView"); }

    Read the article

  • Jquery autocomplete with Dynamic input box.?

    - by Kaps Hasija
    I have done so much R & D for Jquery Auto complete, I found some result but not as much i needed. I am giving you code which are currently i am using . <input type="text" value="|a" name="completeMe" id="Subject" />// This input box will created by Dynamic using forloop // My Jquery Code $(function () { $("#Subject").autocomplete({ source: '/Cataloging/Bib/GetSubject', minLength: 1, select: function (event, ui) { // Do something with "ui.item.Id" or "ui.item.Name" or any of the other properties you selected to return from the action } }); }); // My Action Method public ActionResult GetSubject(string term) { term = term.Substring(2, term.Length-2); return Json(db.BibContents.Where(city => city.Value.StartsWith(term)).Select(city => city.Value), JsonRequestBehavior.AllowGet); } // My code is running with static input but while creating Dynamic I need to use live event but i don't know how can i use Live Event with this code. NOTE: I am using static value of input "|a" after rendering on action i am removing that first two char to make proper search from database. Thanks

    Read the article

  • datepicker not working in chrome

    - by DotnetSparrow
    I have a Jquery UI datepicker control in my asp.net MVC application and it works fine in IE and Firefox but it doens't work in chrome when I click the datepicker button. Here is my Index view: $(function() { $('#datepicker').datepicker({ changeMonth: true, dateFormat: "dd M yy", changeYear: true, showButtonPanel: true, autoSize: true, altField: "input#txtDate", onSelect: function(dateText, inst) { $.ajax({ type: "POST", url: "/LiveGame/Partial3?gameDate=" + dateText, dataType: "html", success: function(result) { var domElement = $(result); $("#dvGames").html(domElement); } }); } }); $("#txtDate").val($.format.date(new Date(), 'dd MMM yyyy')); $('#dvGames').load( '<%= Url.Action("Partial3", "LiveGame") %>', { gameDate: $("#txtDate").val() } ); }); Here is my partial: public ActionResult Partial3(string gameDate) { return PartialView("Partial3", gameDate); } <div id="dvGames" class="cornerdate1"> <%= Url.Action("LiveGame","Partial3") %> </div> <input type="text" id="txtDate" name="txtDate" readonly="readonly" class="cornerdate" /> <input id="datepicker" class="cornerimage" type="image" src="../../Content/images/calendar.gif" alt="date" /> </div>

    Read the article

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