Search Results

Search found 165 results on 7 pages for 'httpverbs'.

Page 6/7 | < Previous Page | 2 3 4 5 6 7  | Next Page >

  • How to check for a null object reference when validating forms in MVC

    - by quakkels
    Hello SO, I'm experimenting with validating forms in the asp.net MVC framework. I'm focusing on server side validation for the time being. I've come across an error that I'm not sure how to rectify. System.NullReferenceException: Object reference not set to an instance of an object. The code that throws the error is: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Exclude="ID")] MembersCreate mc ) { mc.Modules = ModuleListDataContext.GetModuleList(); ViewData.Model = mc; //Validation using ModelState // // //line below errors when form field is empty // if ((string)mc.Member.Username.Trim() == "") ModelState.AddModelError("Member.Username", "Username is required."); if (!ModelState.IsValid) return View(); try { // TODO: Add insert logic here return RedirectToAction("Index","Home"); } catch { return View(); } } When I put spaces in the field it performs exactly as i want, but if I leave the field blank and press submit I get the error. What's the best way to avoid this error and still validate blank form fields? Thanks all -

    Read the article

  • ASP.NET MVC - Wrong redirecting, how to debug?

    - by Xorty
    I am stuck with redirecting problem in ASP.NET MVC project. I have mapped tables via LINQtoSQL and each has unique ID as primary key. I am implementing functionallity of 'CREATE'. Basically, after new value is added into SQL table (which means I pressed Save button), I want to be redirected to Details of this freshly added item. Here's little code how I am doing it : [AcceptVerbs(HttpVerbs.Post), Authorize] public ActionResult Create(Item item) { .... return RedirectToAction("Details", new { id = item.ItemID }); Trouble is, I am never redirected to Details view (I have Details.aspx view for items). When I check CallHierarchy in Visual Studio (2010 pro) the hierarchy is indeed little strange, like this : RedirectToAction(string,object) Calls To 'RedirectToAction' Create Calls To Create (no results) Calls From Create (methods of created instance. From there I'll get back to 'RedirectToAction' and to 'Calls to Create' and 'Calls From Create' etc. etc. - loop Edit Calls From 'RedirectToAction' Not supported I am looking for some tools or more specifically 'know how' (since VS probably has some tools) to debug this kind of situations. PS: rooting is default :"{controller}/{action}/{id}", Thanks

    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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • asp.net mvc postback

    - by user266909
    I have a controller with the following two Edit methods. The edit form displays correctly with all additional dropdown lists from the FormViewModel. However, when I changed some field values and submitted the form. None of the changed fields were saved. The fields in the postbask collection have default or null values. I have another edit form which update another table. On submit, the changed values are saved. Does anyone know why? // GET: /Transfers/Edit/5 public ActionResult Edit(int id) { Transfer transfer = myRepository.GetTransfer(id); if (transfer == null) return View("NotFound"); return View(new TransferFormViewModel(transfer)); } // // POST: /Transfers/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, Transfer collection) { Transfer transfer = vetsRepository.GetTransfer(id); if (transfer == null) return View("NotFound"); else { try { UpdateModel(transfer); vetsRepository.Save(); return RedirectToAction("Details", new { id = transfer.TransfersID }); } catch { ModelState.AddModelErrors(transfer.GetRuleViolations()); return View(new TransferFormViewModel(transfer)); } } }

    Read the article

  • The parameters dictionary contains a null entry for parameter

    - by ognjenb
    <%using (Html.BeginForm("OrderDevice", "ImportXML", FormMethod.Post)) { %> <table id="OrderDevices" class="data-table"> <tr> <th> DeviceId </th> <th> Id </th> <th> OrderId </th> </tr> <% foreach (var item in Model) { %> <tr> <td> <input readonly="readonly" class="" id="DeviceId" type="text" name="<%= Html.Encode(item.DeviceId) %>" value="<%= Html.Encode(item.DeviceId) %>" style="width: 61px" /> </td> <td> <input readonly="readonly" class="" id="c" type="text" name= "<%= Html.Encode(item.Id) %>" value=" <%= Html.Encode(item.Id) %>" style="width: 50px" /> </td> <td> <input readonly="readonly" class="" id="OrderId" type="text" name= " <%= Html.Encode(item.OrderId) %>" value="<%= Html.Encode(item.OrderId) %> " style="width: 49px" /> </td> </tr> <% } %> </table> <input type="submit" value="Create"/> <%} %> My controller action: [AcceptVerbs(HttpVerbs.Post)] public ActionResult OrderDevice(int id) { try { // TODO: Add insert logic here orderdevice ord = new orderdevice(); ord.Id = System.Convert.ToInt32(Request.Form["Id"]); ord.OrderId = System.Convert.ToInt32(Request.Form["OrderId"]); ord.DeviceId = System.Convert.ToInt32(Request.Form["DeviceId"]); XMLEntities.AddToorderdevice(ord); XMLEntities.SaveChanges(); return RedirectToAction("Index"); } catch { return View("Index"); } } When post a form I have this error: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult OrderDevice(Int32)' in 'MvcKVteam.Controllers.ImportXMLController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters How fix it?

    Read the article

  • ASP.NET MVC ViewModel Pattern

    - by Omu
    EDIT: I made something much better to fill and read data from a view using ViewModels, called it ValueInjecter. http://valueinjecter.codeplex.com/documentation using the ViewModel to store the mapping logic was not such a good idea because there was repetition and SRP violation, but now with the ValueInjecter I have clean ViewModels and dry mapping code I made a ViewModel pattern for editing stuff in asp.net mvc this pattern is usefull when you have to make a form for editing an entity and you have to put on the form some dropdowns for the user to choose some values public class OrganisationViewModel { //paramterless constructor required, cuz we are gonna get an OrganisationViewModel object from the form in the post save method public OrganisationViewModel() : this(new Organisation()) {} public OrganisationViewModel(Organisation o) { Organisation = o; Country = new SelectList(LookupFacade.Country.GetAll(), "ID", "Description", CountryKey); } //that's the Type for whom i create the viewmodel public Organisation Organisation { get; set; } #region DropDowns //for each dropdown i have a int? Key that stores the selected value public IEnumerable<SelectListItem> Country { get; set; } public int? CountryKey { get { if (Organisation.Country != null) { return Organisation.Country.ID; } return null; } set { if (value.HasValue) { Organisation.Country = LookupFacade.Country.Get(value.Value); } } } #endregion } and that's how i use it public ViewResult Edit(int id) { var model = new OrganisationViewModel(organisationRepository.Get(id)); return View(model); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(OrganisationViewModel model) { organisationRepository.SaveOrUpdate(model.Organisation); return RedirectToAction("Index"); } and the markup <p> <label for="Name"> Name:</label> <%= Html.Hidden("Organisation.ID", Model.Organisation.ID)%> <%= Html.TextBox("Organisation.Name", Model.Organisation.Name)%> <%= Html.ValidationMessage("Organisation.Name", "*")%> </p> <p> ... <label for="CountryKey"> Country:</label> <%= Html.DropDownList("CountryKey", Model.Country, "please select") %> <%= Html.ValidationMessage("CountryKey", "*") %> </p> so tell me what you think about it

    Read the article

  • SelectList in Asp-mvc and data from the database

    - by George
    Hello guys. I'm having some troubles with SelectList in ASP.MVC. Here is the issue: I have a Create View and begind a ViewModel model. The page load just fine (GET verb). But when posting, something happens, and my model is considered invalid, and it cannot insert. Here's what i've tried so far. public class DefinitionFormViewModel { private Repository<Category> categoryRepository = new Repository<Category>(); public Definition ViewDefinition { get; private set; } public SelectList Categories { get; private set; } public DefinitionFormViewModel(Definition def) { ViewDefinition = def; // here i wanted to place it directly, like shown in NerdDinner Tutorial // new SelectList(categoryRepository.All(),ViewDefinition.Category); Categories = new SelectList(categoryRepository.All(), "CategoryId", "CategoryName", ViewDefinition.CategoryId); } } // pageview which inherits DefinitionFormViewModel <div class=editor-field"> <%= Html.DropDownList("Category",Model.Categories) %> <%= Html.ValidationMessageFor(model => Model.ViewDefinition.Category) %> </div> // controller methods [Authorize] public ActionResult Create() { Definition definition = new Definition(); return View(new DefinitionFormViewModel(definition)); } [AcceptVerbs(HttpVerbs.Post), Authorize] public ActionResult Create(int id,Definition definition) { Term term = termRepository.SingleOrDefault(t => t.TermId == id); if (term == null) { return View("NotFound", new NotFoundModel("Termo não encontrado", "Termo não encontrado", "Nos desculpe, mas não conseguimos encontrar o termo solicitado.", "Indíce de Termos", "Index", "Term")); } else { if (ModelState.IsValid) { try { definition.TermId = term.TermId; definition.ResponsibleUser = User.Identity.Name; UpdateModel(definition); term.Definitions.Add(definition); termRepository.SaveAll(); return RedirectToAction("Details", "Term", new { id = term.TermId }); } catch (System.Data.SqlClient.SqlException sqlEx) { ModelState.AddModelError("DatabaseError", "Houve um erro na inserção desta nova definição"); } catch { foreach (RuleViolation rv in definition.GetRuleViolations()) { ModelState.AddModelError(rv.PropertyName, rv.ErrorMessage); } } } } return View(new DefinitionFormViewModel(definition)); } I'm sorry about the long post, but I cant figure this out. I got no graphic errors or exceptions. My execution terminates in if (ModelState.IsValid). Thanks for your time George

    Read the article

  • MVC Partial View Not Refreshing when using JSON data

    - by 40-Love
    I have a dropdown that I'm using to refresh a div with checkboxes. I am trying to figure out why my view is not refreshing if I pass in data in JSON format. If I pass in just a regular string, the view refreshes. If I pass in JSON data, the view does not refresh. If I step through the code in the Partial view, I can see the correct number of records are being passed in, however the view doesn't get refreshed with the correct number of checkboxes. I tried to add some cache directives, it didn't work. This doesn't work: $(function () { $('#ddlMoveToListNames').change(function () { var item = $(this).val(); var selectedListID = $('#ddlListNames').val(); var checkValues = $('input[name=c]:checked').map(function () { return $(this).val(); }).toArray(); $.ajax({ url: '@Url.Action("Test1", "WordList")', type: 'POST', cache: false, data: JSON.stringify({ words: checkValues, moveToListID: item, selectedListID: selectedListID }), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (result) { } }) .done(function (partialViewResult) { $("#divCheckBoxes").replaceWith(partialViewResult); }); }); }); This works: $(function () { $('#ddlMoveToListNames').change(function () { var item = $(this).val(); var selectedListID = $('#ddlListNames').val(); var checkValues = $('input[name=c]:checked').map(function () { return $(this).val(); }).toArray(); $.ajax({ url: '@Url.Action("Test1", "WordList")', type: 'POST', cache: false, data: { selectedListID: item }, success: function (result) { } }) .done(function (partialViewResult) { $("#divCheckBoxes").replaceWith(partialViewResult); }); }); }); Partial View: @model WLWeb.Models.MyModel <div id="divCheckBoxes"> @foreach (var item in Model.vwWordList) { @Html.Raw("<label><input type='checkbox' value='" + @Html.DisplayFor(modelItem => item.Word) + "' name='c'> " + @Html.DisplayFor(modelItem => item.Word) + "</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); } </div> Controller: [AcceptVerbs(HttpVerbs.Post)] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] public PartialViewResult Test1(MyModel vm, string[] words, string moveToListID, string selectedListID) { int listNameID = Convert.ToInt32(moveToListID); List<vwWordList> lst = db.vwWordLists.Where(s => s.Word.StartsWith("wa") && s.ListID == listNameID).ToList(); vm.vwWordList = lst; return PartialView("Partial1", vm); } View: @Html.DropDownListFor(x => Model.FilterViewModel.MoveToListNameID, Model.FilterViewModel.MoveToListNameList, new { @id = "ddlMoveToListNames", style = "width:100px;" })

    Read the article

  • ActionResult - Service

    - by cem
    I bored, writing same code for service and ui. Then i tried to write a converter for simple actions. This converter, converting Service Results to MVC result, seems like good solution for me but anyway i think this gonna opposite MVC pattern. So here, I need help, what you think about algorithm - is this good or not? Thanks ServiceResult - Base: public abstract class ServiceResult { public static NoPermissionResult Permission() { return new NoPermissionResult(); } public static SuccessResult Success() { return new SuccessResult(); } public static SuccessResult<T> Success<T>(T result) { return new SuccessResult<T>(result); } protected ServiceResult(ServiceResultType serviceResultType) { _resultType = serviceResultType; } private readonly ServiceResultType _resultType; public ServiceResultType ResultType { get { return _resultType; } } } public class SuccessResult<T> : ServiceResult { public SuccessResult(T result) : base(ServiceResultType.Success) { _result = result; } private readonly T _result; public T Result { get { return _result; } } } public class SuccessResult : SuccessResult<object> { public SuccessResult() : this(null) { } public SuccessResult(object o) : base(o) { } } Service - eg. ForumService: public ServiceResult Delete(IVUser user, int id) { Forum forum = Repository.GetDelete(id); if (!Permission.CanDelete(user, forum)) { return ServiceResult.Permission(); } Repository.Delete(forum); return ServiceResult.Success(); } Controller: public class BaseController { public ActionResult GetResult(ServiceResult result) { switch (result.ResultType) { case ServiceResultType.Success: var successResult = (SuccessResult)result; return View(successResult.Result); break; case ServiceResultType.NoPermission: return View("Error"); break; default: return View(); break; } } } [HandleError] public class ForumsController : BaseController { [ValidateAntiForgeryToken] [Transaction] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id) { ServiceResult result = ForumService.Delete(WebUser.Current, id); /* Custom result */ if (result.ResultType == ServiceResultType.Success) { TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = "The forum was successfully deleted."; return this.RedirectToAction(ec => Index()); } /* Custom result */ /* Execute Permission result etc. */ TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()] = "A problem was encountered preventing the forum from being deleted. " + "Another item likely depends on this forum."; return GetResult(result); } }

    Read the article

  • ASP.NET MVC: How can I explain an invalid type violation to an end-user with Html.ValidationSummary?

    - by Terminal Frost
    Serious n00b warning here; please take mercy! So I finished the Nerd Dinner MVC Tutorial and I'm now in the process of converting a VB.NET application to ASP.NET MVC using the Nerd Dinner program as a sort of rough template. I am using the "IsValid / GetRuleViolations()" pattern to identify invalid user input or values that violate business rules. I am using LINQ to SQL and am taking advantage of the "OnValidate()" hook that allows me to run the validation and throw an application exception upon trying to save changes to the database via the CustomerRepository class. Anyway, everything works well, except that by the time the form values reach my validation method invalid types have already been converted to a default or existing value. (I have a "StreetNumber" property that is an integer, though I imagine this would be a problem for DateTime or any other non-strings as well.) Now, I am guessing that the UpdateModel() method throws an exception and then alters the value because the Html.ValidationMessage is displayed next to the StreetNumber field but my validation method never sees the original input. There are two problems with this: While the Html.ValidationMessage does signal that something is wrong, there is no corresponding entry in the Html.ValidationSummary. If I could even get the exception message to show up there indicating an invalid cast or something that would be better than nothing. My validation method which resides in my Customer partial class never sees the original user input so I do not know if the problem is a missing entry or an invalid type. I can't figure out how I can keep my validation logic nice and neat in one place and still get access to the form values. I could of course write some logic in the View that processes the user input, however that seems like the exact opposite of what I should be doing with MVC. Do I need a new validation pattern or is there some way to pass the original form values to my model class for processing? CustomerController Code // POST: /Customers/Edit/[id] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection formValues) { Customer customer = customerRepository.GetCustomer(id); try { UpdateModel(customer); customerRepository.Save(); return RedirectToAction("Details", new { id = customer.AccountID }); } catch { foreach (var issue in customer.GetRuleViolations()) ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage); } return View(customer); }

    Read the article

  • How to page multiple data sets in ASP.NET MVC

    - by REA_ANDREW
    On a single view I will have three sets of paged data. Which means for each model I will have The Objects The Page Index The Page Size My initial thought was for example: public class PagedModel<T> where T:class { public IList<T> Objects { get; set; } public int ModelPageIndex { get; set; } public int ModelPageSize { get; set; } } Then having a model which is to be supplied to the action as for example: public class TypesViewModel { public PagedModel<ObjectA> Types1 { get; set; } public PagedModel<ObjectB> Typed2 { get; set; } public PagedModel<ObjectC> Types3 { get; set; } } So if I then for example have the Index view inherit from the type: System.Web.Mvc.ViewPage<uk.co.andrewrea.forum.Web.Models.TypesViewModel> Now my initial aciton method for the index is simply: public ActionResult Index() { var forDisplayPurposes = new TypesViewModel(); return View(forDisplayPurposes); } If I then want to page, it is here where I am struggling to decide which action to take. Lets say that I select the next page of the Types2 PageModel. What should the action look like for this in order to return the new view showing the second page of the Types2 PageModel I was thinking possibly to duplicate the action but use it with POST [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(TypesViewModel model) { return View(model); } Is this a good way to approach it. I understand there is always Session, but I was just wondering how such a thing is achieved currently out there. If any best methods have been mutually accepted and things. So simply, one page with multiple paged models. How to persist the data for each using a wrapper model. Which way should you pass in the model and which way should you page the data, i.e. Form Post Lastly, I have seen the routes take this into account i.e. {controller}/{action}/{id}/{pageindex}/{pagesize} but this only accounts for one model and I do not really wwant to repeat the pagesize and pageindex values for the number of models I have inside the wrapper model. Thanks for your time!! Andrew

    Read the article

  • Image Preview in ASP.NET MVC

    - by imran_ku07
      Introduction :         Previewing an image is a great way to improve the UI of your site. Also it is always best to check the file type, size and see a preview before submitting the whole form. There are some ways to do this using simple JavaScript but not work in all browsers (like FF3).In this Article I will show you how do this using ASP.NET MVC application. You also see how this will work in case of nested form.   Description :          Create a new ASP.NET MVC project and then add a file upload and image control into your View. <form id="form1" method="post" action="NerdDinner/ImagePreview/AjaxSubmit">            <table>                <tr>                    <td>                        <input type="file" name="imageLoad1" id="imageLoad1"  onchange="ChangeImage(this,'#imgThumbnail')" />                    </td>                </tr>                <tr>                    <td align="center">                        <img src="images/TempImage.gif" id="imgThumbnail" height="200px" width="200px">                     </td>                </tr>            </table>        </form>           Note that here NerdDinner is refers to the virtual directory name, ImagePreview is the Controller and ImageLoad is the action name which you will see shortly          I will use the most popular jQuery form plug-in, that turns a form into an AJAX form with very little code. Therefore you must get these from Jquery site and then add these files into your page.          <script src="NerdDinner/Scripts/jquery-1.3.2.js" type="text/javascript"></script>        <script src="NerdDinner/Scripts/jquery.form.js" type="text/javascript"></script>            Then add the javascript function. <script type="text/javascript">function ChangeImage(fileId,imageId){ $("#form1").ajaxSubmit({success: function(responseText){ var d=new Date(); $(imageId)[0].src="NerdDinner/ImagePreview/ImageLoad?a="+d.getTime(); } });}</script>             This function simply submit the form named form1 asynchronously to ImagePreviewController's method AjaxSubmit and after successfully receiving the response, it will set the image src property to the action method ImageLoad. Here I am also adding querystring, preventing the browser to serve the cached image.           Now I will create a new Controller named ImagePreviewController. public class ImagePreviewController : Controller { [AcceptVerbs(HttpVerbs.Post)] public ActionResult AjaxSubmit(int? id) { Session["ContentLength"] = Request.Files[0].ContentLength; Session["ContentType"] = Request.Files[0].ContentType; byte[] b = new byte[Request.Files[0].ContentLength]; Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength); Session["ContentStream"] = b; return Content( Request.Files[0].ContentType+";"+ Request.Files[0].ContentLength ); } public ActionResult ImageLoad(int? id) { byte[] b = (byte[])Session["ContentStream"]; int length = (int)Session["ContentLength"]; string type = (string)Session["ContentType"]; Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = type; Response.BinaryWrite(b); Response.Flush(); Session["ContentLength"] = null; Session["ContentType"] = null; Session["ContentStream"] = null; Response.End(); return Content(""); } }             The AjaxSubmit action method will save the image in Session and return content type and content length in response. ImageLoad action method will return the contents of image in response.Then clear these Sessions.           Just run your application and see the effect.   Checking Size and Content Type of File:          You may notice that AjaxSubmit action method is returning both content type and content length. You can check both properties before submitting your complete form.     $(myform).ajaxSubmit({success: function(responseText)            {                                var contentType=responseText.substring(0,responseText.indexOf(';'));                var contentLength=responseText.substring(responseText.indexOf(';')+1);                // Here you can do your validation                var d=new Date();                $(imageId)[0].src="http://weblogs.asp.net/MoneypingAPP/ImagePreview/ImageLoad?a="+d.getTime();            }        });  Handling Nested Form Case:          The above code will work if you have only one form. But this is not the case always.You may have a form control which wraps all the controls and you do not want to submit the whole form, just for getting a preview effect.           In this case you need to create a dynamic form control using JavaScript, and then add file upload control to this form and submit the form asynchronously  function ChangeImage(fileId,imageId)         {            var myform=document.createElement("form");                    myform.action="NerdDinner/ImagePreview/AjaxSubmit";            myform.enctype="multipart/form-data";            myform.method="post";            var imageLoad=document.getElementById(fileId).cloneNode(true);            myform.appendChild(imageLoad);            document.body.appendChild(myform);            $(myform).ajaxSubmit({success: function(responseText)                {                                    var contentType=responseText.substring(0,responseText.indexOf(';'));                    var contentLength=responseText.substring(responseText.indexOf(';')+1);                    var d=new Date();                    $(imageId)[0].src="http://weblogs.asp.net/MoneypingAPP/ImagePreview/ImageLoad?a="+d.getTime();                    document.body.removeChild(myform);                }            });        }            You also need append the child in order to send request and remove them after receiving response.

    Read the article

  • ASP.NET MVC File Upload Error - "The input is not a valid Base-64 string"

    - by Justin
    Hey all, I'm trying to add a file upload control to my ASP.NET MVC 2 form but after I select a jpg and click Save, it gives the following error: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. Here's the view: <% using (Html.BeginForm("Save", "Developers", FormMethod.Post, new {enctype = "multipart/form-data"})) { %> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> Login Name </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.LoginName) %> <%: Html.ValidationMessageFor(model => model.LoginName) %> </div> <div class="editor-label"> Password </div> <div class="editor-field"> <%: Html.Password("Password") %> <%: Html.ValidationMessageFor(model => model.Password) %> </div> <div class="editor-label"> First Name </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.FirstName) %> <%: Html.ValidationMessageFor(model => model.FirstName) %> </div> <div class="editor-label"> Last Name </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.LastName) %> <%: Html.ValidationMessageFor(model => model.LastName) %> </div> <div class="editor-label"> Photo </div> <div class="editor-field"> <input id="Photo" name="Photo" type="file" /> </div> <p> <%: Html.Hidden("DeveloperID") %> <%: Html.Hidden("CreateDate") %> <input type="submit" value="Save" /> </p> </fieldset> <% } %> And the controller: //POST: /Secure/Developers/Save/ [AcceptVerbs(HttpVerbs.Post)] public ActionResult Save(Developer developer) { //get profile photo. var upload = Request.Files["Photo"]; if (upload.ContentLength > 0) { string savedFileName = Path.Combine( ConfigurationManager.AppSettings["FileUploadDirectory"], "Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg"); upload.SaveAs(savedFileName); } developer.UpdateDate = DateTime.Now; if (developer.DeveloperID == 0) {//inserting new developer. DataContext.DeveloperData.Insert(developer); } else {//attaching existing developer. DataContext.DeveloperData.Attach(developer); } //save changes. DataContext.SaveChanges(); //redirect to developer list. return RedirectToAction("Index"); } Thanks, Justin

    Read the article

  • ASP.NET MVC : AJAX ActionLink - Persist Data

    - by Mio
    Hi guys, I'm really new at this and I was searching the web for an answer to my question and I couldn't find it, so here I am posting my question :) I'm trying to create a new record in my table Facility. For my goreign keys I'm displaying the choices in tables instead of a dropdowns. When the user clicks on the select link which is an Ajax.ActionLink(), I wanna retrieve the right record from the DB and set the foreign key of my object Facility to the one slected and replace the Div by a new Partial View. The problem is when I try to submit the form, the Facility object doesnt seem to have the foreign key that I've just set in my ajax fuction in my controller. And if the user has enter some data in the other fields of the create form, I don't them to lose what they already entered. Here's my code. Model only contains a Facility. public ActionResult Create() { Model.Facility = new Facility(); return View(Model); } This is part of my Create View <div id="FacilityTypePartialView"> <% Html.RenderPartial("FacilityType"); %> </div> This is my Partial View FacilityType <% if (Model.IsNewFacility()) { %> <p> Id: <%= Html.Encode(Model.Facility.FacilityType.FId)%> </p> <p> Type: <%= Html.Encode(Model.Facility.FacilityType.FType)%> </p> <p> Description: <%= Html.Encode(Model.Facility.FacilityType.FDescription) %> </p> <% } %> <p> <%= Html.ActionLink("Manage Facility Type", "Index","FacilityType") %> </p> <table id="FacilityTypesList"> <tr> <th> Select </th> <th> FId </th> <th> FType </th> <th> FDescription </th> </tr> <% foreach (var item in Model.GetFacilityTypes()) { %> <tr> <td> <%=Ajax.ActionLink("Select", "FacilityTypeSelect", new { id = item.FId}, new AjaxOptions { UpdateTargetId = "FacilityTypePartialView" })%> </td> <td> <%= Html.Encode(item.FId) %> </td> <td> <%= Html.Encode(item.FType) %> </td> <td> <%= Html.Encode(item.FDescription) %> </td> </tr> <% } %> </table> Here's y Ajax Funcion public PartialViewResult FacilityTypeSelect(int id) { Facility facility = new Facility(); facility.FacilityType = _repository.GetFacilityType(id); Model.Facility = facility; if (this.Request.IsAjaxRequest() == false) { return PartialView("FacilityType/FacilityType", Model); } else { return PartialView("FacilityType/FacilityTypeSelected", Model); } } Finally, my Post method [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create( Facility facility) { Model.Facility = facility; if (ModelState.IsValid) { try { _repository.AddEntity(facility); _repository.Save(); return RedirectToAction("Details", new { id = facility.Id }); } catch { } } return View("Create", Model); } My Faciliy object coming from the View have the Facility.FacilityType set to nothing.

    Read the article

  • ASP.NET MVC 2 - Saving child entities on form submit

    - by Justin
    Hey, I'm using ASP.NET MVC 2 and am struggling with saving child entities. I have an existing Invoice entity (which I create on a separate form) and then I have a LogHours view that I'd like to use to save InvoiceLog's, which are child entities of Invoice. Here's the view: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TothSolutions.Data.Invoice>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Log Hours </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server"> <script type="text/javascript"> $(document).ready(function () { $("#InvoiceLogs_0__Description").focus(); }); </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Log Hours</h2> <% using (Html.BeginForm("SaveHours", "Invoices")) {%> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <table> <tr> <th>Date</th> <th>Description</th> <th>Hours</th> </tr> <% int index = 0; foreach (var log in Model.InvoiceLogs) { %> <tr> <td><%: log.LogDate.ToShortDateString() %></td> <td><%: Html.TextBox("InvoiceLogs[" + index + "].Description")%></td> <td><%: Html.TextBox("InvoiceLogs[" + index + "].Hours")%></td> <td>Hours</td> </tr> <% index++; } %> </table> <p> <%: Html.Hidden("InvoiceID") %> <%: Html.Hidden("CreateDate") %> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <div> <%: Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> And here's the controller code: //GET: /Secure/Invoices/LogHours/ public ActionResult LogHours(int id) { var invoice = DataContext.InvoiceData.Get(id); if (invoice == null) { throw new Exception("Invoice not found with id: " + id); } return View(invoice); } //POST: /Secure/Invoices/SaveHours/ [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveHours([Bind(Exclude = "InvoiceLogs")]Invoice invoice) { TryUpdateModel(invoice.InvoiceLogs, "InvoiceLogs"); invoice.UpdateDate = DateTime.Now; invoice.DeveloperID = DeveloperID; //attaching existing invoice. DataContext.InvoiceData.Attach(invoice); //save changes. DataContext.SaveChanges(); //redirect to invoice list. return RedirectToAction("Index"); } And the data access code: public static void Attach(Invoice invoice) { var i = new Invoice { InvoiceID = invoice.InvoiceID }; db.Invoices.Attach(i); db.Invoices.ApplyCurrentValues(invoice); } In the SaveHours action, it properly sets the values of the InvoiceLog entities after I call TryUpdateModel but when it does SaveChanges it doesn't update the database with the new values. Also, if you manually update the values of the InvoiceLog entries in the database and then go to this page it doesn't populate the textboxes so it's clearly not binding correctly. Thanks, Justin

    Read the article

  • Simple Convention Automapper for two-way Mapping (Entities to/from ViewModels)

    - by Omu
    UPDATE: this stuff has evolved into a nice project, see it at http://valueinjecter.codeplex.com check this out, I just wrote a simple automapper, it takes the value from the property with the same name and type of one object and puts it into another, and you can add exceptions (ifs, switch) for each type you may need so tell me what do you think about it ? I did it so I could do something like this: Product –> ProductDTO ProductDTO –> Product that's how it begun: I use the "object" type in my Inputs/Dto/ViewModels for DropDowns because I send to the html a IEnumerable<SelectListItem> and I receive a string array of selected keys back public void Map(object a, object b) { var pp = a.GetType().GetProperties(); foreach (var pa in pp) { var value = pa.GetValue(a, null); // property with the same name in b var pb = b.GetType().GetProperty(pa.Name); if (pb == null) { //no such property in b continue; } if (pa.PropertyType == pb.PropertyType) { pb.SetValue(b, value, null); } } } UPDATE: the real usage: the Build methods (Input = Dto): public static TI BuildInput<TI, T>(this T entity) where TI: class, new() { var input = new TI(); input = Map(entity, input) as TI; return input; } public static T BuildEntity<T, TI, TR>(this TI input) where T : class, new() where TR : IBaseAdvanceService<T> { var id = (long)input.GetType().GetProperty("Id").GetValue(input, null); var entity = LocatorConfigurator.Resolve<TR>().Get(id) ?? new T(); entity = Map(input, entity) as T; return entity; } public static TI RebuildInput<T, TI, TR>(this TI input) where T: class, new() where TR : IBaseAdvanceService<T> where TI : class, new() { return input.BuildEntity<T, TI, TR>().BuildInput<TI, T>(); } in the controller: public ActionResult Create() { return View(new Organisation().BuildInput<OrganisationInput, Organisation>()); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(OrganisationInput o) { if (!ModelState.IsValid) { return View(o.RebuildInput<Organisation,OrganisationInput, IOrganisationService>()); } organisationService.SaveOrUpdate(o.BuildEntity<Organisation, OrganisationInput, IOrganisationService>()); return RedirectToAction("Index"); } The real Map method public static object Map(object a, object b) { var lookups = GetLookups(); var propertyInfos = a.GetType().GetProperties(); foreach (var pa in propertyInfos) { var value = pa.GetValue(a, null); // property with the same name in b var pb = b.GetType().GetProperty(pa.Name); if (pb == null) { continue; } if (pa.PropertyType == pb.PropertyType) { pb.SetValue(b, value, null); } else if (lookups.Contains(pa.Name) && pa.PropertyType == typeof(LookupItem)) { pb.SetValue(b, (pa.GetValue(a, null) as LookupItem).GetSelectList(pa.Name), null); } else if (lookups.Contains(pa.Name) && pa.PropertyType == typeof(object)) { pb.SetValue(b, pa.GetValue(a, null).ReadSelectItemValue(), null); } else if (pa.PropertyType == typeof(long) && pb.PropertyType == typeof(Organisation)) { pb.SetValue(b, pa.GetValue<long>(a).ReadOrganisationId(), null); } else if (pa.PropertyType == typeof(Organisation) && pb.PropertyType == typeof(long)) { pb.SetValue(b, pa.GetValue<Organisation>(a).Id, null); } } return b; }

    Read the article

< Previous Page | 2 3 4 5 6 7  | Next Page >