Search Results

Search found 59301 results on 2373 pages for 'asp net ajax'.

Page 89/2373 | < Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >

  • Javascript calls to an Ajax WebMethod. How to get multiple output params returned?

    - by George
    OK, I know how to call a simple old fashion asmx webservice webthod that returns a single value as a function return result. But what if I want to return multiple output params? My current approach is to separate the params by a dividing character and parse them on teh client. Is there a better way. Here's how I return a single function result. How do I return multiple output values? <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> function CallHelloWebMethod() { WebService.Hello(OnComplete1, OnTimeOut, OnError); } function OnComplete1(arg) { alert(arg); } function OnTimeOut(arg) { } <WebMethod()> Public Function Hello(ByVal x As String) As String Return "Hello " & x End Function

    Read the article

  • Convert asp.net webforms logic to asp.net MVC

    - by gmcalab
    I had this code in an old asp.net webforms app to take a MemoryStream and pass it as the Response showing a PDF as the response. I am now working with an asp.net MVC application and looking to do this this same thing, but how should I go about showing the MemoryStream as PDF using MVC? Here's my asp.net webforms code: private void ShowPDF(MemoryStream ms) { try { //get byte array of pdf in memory byte[] fileArray = ms.ToArray(); //send file to the user Page.Response.Cache.SetCacheability(HttpCacheability.NoCache); Page.Response.Buffer = true; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.Charset = string.Empty; Response.ContentType = "application/pdf"; Response.AddHeader("content-length", fileArray.Length.ToString()); Response.AddHeader("Content-Disposition", "attachment;filename=TID.pdf;"); Response.BinaryWrite(fileArray); Response.Flush(); Response.Close(); } catch { // and boom goes the dynamite... } }

    Read the article

  • asp.net MVC partial view

    - by DotnetSparrow
    Hi all: I have created a function for load event like this: $(function() { $('#dvGames').load( '<%= Url.Action("Partial3", "LiveGame") %>',{ gameDate: '2011-03-06' } ); }); and it works. Also, I have created a function for date change like this: $(function() { $('#datepicker').datepicker({ onSelect: function(dateText, inst) { $.ajax({ type: "POST", url: "/LiveGame/Partial3", data: "gameDate=" + dateText, success: function(result) { alert(result); var domElement = $(result); // create element from html $("#dvGames").append(domElement); // append to end of list } }); } }); }); but it doesnt work. neither it goes in controller action. My controller action is: public ActionResult Partial3(string gameDate) { return PartialView("Partial3"); } Please suggest me solution to this.

    Read the article

  • How to change the layout of the CreateUserWizard control?

    - by Bazzz
    How to change just the layout (template) of the CreateUserWizard control programmatically? I would to define another layout (not using the horrid table) but continue to use all the event handling and the creation of the user of the CreateUserWizard control. Just for reference, the following code doesn't work, and produces an unexpected result not representing my Template at all. The "InstantiateIn" method of the ITemplate is not called. public partial class b : System.Web.UI.Page { protected void Page_Init(object sender, EventArgs e) { CreateUserWizard createUserWizard = new CreateUserWizard(); createUserWizard.CreateUserStep.ContentTemplate = new Template(); Panel1.Controls.Add(createUserWizard); } } public class Template : ITemplate { void ITemplate.InstantiateIn(Control container) { container.Controls.Add(new TextBox() { ID = "UserName" }); container.Controls.Add(new TextBox() { ID = "Password" }); container.Controls.Add(new TextBox() { ID = "ConfirmPassword" }); container.Controls.Add(new TextBox() { ID = "Email" }); container.Controls.Add(new PlaceHolder() { ID = "ErrorMessage" }); } } }

    Read the article

  • Filter of Data in Gridview logical error please using asp.net

    - by RajuBabli Abbasi
    I wanted to filter the Data in asp.net but my Data is not filtering i have some logical error So please help me for this case i will be very thanks full to those who will help me please consider my code and replay me with code if you can so please i am waiting for your replay thanks again my asp.cs file is protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DisplayStudentInformation(); } } private void DisplayStudentInformation() { string filter = "%" + filterTextBox.Text + "%"; if (filter == String.Empty) filter = "%"; try { using (SqlDataReader reader = DAC.GetCompanyInformation(filter)) {//reader.Read(); StudentGridView.DataSource = reader; StudentGridView.DataBind(); } } catch (SqlException ex) { StatusLabel.Text = ex.Message; } } my .aspx file is asp:Table ID="Tabel" runat ="server" asp:TableRow asp:TableCell asp:Label ID="filterLabel" runat ="server" Text ="Company Name Filter:" AssociatedControlID="filterTextBox" /asp:TableCell asp:TableCell asp:TextBox ID="filterTextBox" runat="server" MaxLength ="50" /asp:TableCell asp:TableCell asp:Button ID="refreshButton" runat ="server" Text ="Filter" CausesValidation="false" / /asp:TableCell /asp:TableRow /asp:Table My DAC file is public static SqlDataReader GetCompanyInformation(string filter) { SqlDataReader reader; string sql = "SELECT * FROM Student WHERE LastName LIKE @prmLastName "; using(SqlCommand command = new SqlCommand (sql,ConnectionManager.GetConnection())) {//In ExecuteReader we pass the CommandBehavior as singleResult because we need the Single result and also passing the close connection when Datais retriev // command.Parameters.Add("@prmLastName", SqlDbType.VarChar, 25).Value = filter; command.Parameters.AddWithValue("@prmLastName", filter); reader = command.ExecuteReader(CommandBehavior.SingleResult | CommandBehavior.CloseConnection); } return reader; } Note:- When i don't use the If(!Ispostback) Condition and simply pass the DisplayStudentInformation(); method in my page load then Data can be filter but with If(!IspostBack ) condition which is also important for updating the data and for other purpose . Data can be filter . Se aim of the expert is that Filter the Data in a gridview using condition of IF(!IspostBack ) means without the removing is post back condition Filter the Data . I have been ask other about this question but no body solve this so please help me i will be very thanks full to you all ok

    Read the article

  • mvc4 receive form in a controller

    - by Marco Dinatsoli
    i have a form in html and i want to submit it to a controler what i have tried @using (Html.BeginForm("RegisterApartmentOwner", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <p> <label>First Name</label> <input type="text" placeholder="Enter your first Name" name="firstName" /> <span class="errorMessage"></span> </p> <p> <label>Last Name</label> <input type="text" placeholder="Enter your last Name" /> <span class="errorMessage"></span> </p> <p> <label>Password</label> <input type="text" placeholder="Enter your password" name="Password"/> <span class="errorMessage"></span> </p> <p> <label>Password Again</label> <input type="text" placeholder="Enter your password again" name="Password2"/> <span class="errorMessage"></span> </p> <p> <label>Mobile Number</label> <input type="text" placeholder="Enter your mobile number" /> <span class="errorMessage"></span> </p> <p> <input type="submit" value="Register" class="submit"/> </p> } </div> and in the controller i receive the submit in this function public String RegisterTenant() { return "done"; } i can see the done message, however, i want to receive the values of the input that i used in the form, how please? i just to know what to receive the form in the controller

    Read the article

  • ASP.NET how to save textbox in database?

    - by mahsoon
    I used some textboxes to get some info from users + a sqldatasource <tr> <td class="style3" colspan="3" style="font-size: medium; font-family: 'B Nazanin'; font-weight: bold; position: relative; right: 170px" > &nbsp; ????? ??????? ????</td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;&nbsp; <asp:Label ID="Label1" runat="server" Text=" ???: " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="FirstName" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ErrorMessage="???? ???? ??? ?????? ???" ControlToValidate="FirstName">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;&nbsp;<asp:Label ID="Label2" runat="server" Text=" ??? ????????: " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="LastName" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Display="Dynamic" ErrorMessage="???? ???? ??? ???????? ?????? ???" ControlToValidate="LastName">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;&nbsp;<asp:Label ID="Label3" runat="server" Text=" ????? ???????? : " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="StudentNumber" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Display="Dynamic" ErrorMessage="???? ???? ????? ???????? ?????? ???" ControlToValidate="StudentNumber">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;<asp:Label ID="Label4" runat="server" Text="  ????? ???? : " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="DateOfBirth" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="????? ???? ?????? ?? ???? ??????" Operator="DataTypeCheck" Type="Date" ControlToValidate="dateOfBirth"></asp:CompareValidator> </td> </tr> <tr> <td class="style3"> &nbsp;</td> <td class="style2"> <asp:Button ID="SaveButton" runat="server" Text=" ????? ???????" Width="102px" style="margin-right: 15px; height: 26px;" /> </td> <td class="style4"> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString1 %>" SelectCommand="SELECT aspnet_personalInformation.FirstName, aspnet_personalInformation.LastName, aspnet_personalInformation.StudentNumber, aspnet_personalInformation.DateOfBirth FROM aspnet_personalInformation INNER JOIN aspnet_Users ON aspnet_personalInformation.UserId = aspnet_Users.UserId WHERE aspnet_personalInformation.UserId=aspnet_Users.UserId ORDER BY aspnet_personalInformation.LastName" InsertCommand="INSERT INTO aspnet_PersonalInformation(UserId) SELECT UserId FROM aspnet_Profile"> </asp:SqlDataSource> </td> </tr> </table> i wanna save firstname lastname studentnumber and dateofbirth in aspnet_personalinformation table in database but before that, i fill one column of aspnet_personalinformation table named UserId by inserting sql command with aspnet_profile.userid now by running this code my table has still blankes protected void SaveButton_Click(object sender, EventArgs e) { string str= "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True"; SqlConnection con = new SqlConnection(str); con.Open(); string query = "INSERT INTO aspnet_PersonalInformation( FirstName, LastName,StudentNumber,DateOfBirth) VALUES ('" + this.FirstName.Text + "','" + this.LastName.Text + "','" + this.StudentNumber.Text + "','" + this.DateOfBirth.Text + "') where aspnet_PersonalInformation.UserId=aspnet_Profile.UserID"; SqlCommand cmd=new SqlCommand(query,con); cmd.ExecuteNonQuery(); con.Close(); } but it doesn't work help me plz

    Read the article

  • Retreive value from model into view ib MVC 3

    - by prerna
    public class HomeController : Controller { public ActionResult Index() { return View(); } /* public string Browse() { return "Hello from Browse"; public string Details(int id) { string message = "Store.Details, ID = " + id; return message; // return "Hello from Details"; }*/ public ActionResult Details(int id) { var album = new Album { Title = "Album " + id }; return View(album); } } I am new to MVC 3 ,My View is Details.aspx without Razor engine. <html> <head runat="server"> <title>Details</title> </head> <body> <div> </div> </body> </html> Can anyone help

    Read the article

  • How do I do multipled level routes best in MVC

    - by Lilja
    I have a site where I would like an URL like: /Some maincategory name/{id}/Some subcategory name/{id}/Some item name/{id} I include the IDs of each level since the name is not unique. This is doable but I have to create a new routing for each level. My Html.ActionLink also looks nasty. Each level has it's own controller since the levels are completely different. The URLs could be something like this: _/Birds/2/Waders/4/Flamingos/23_ _/Mammals/5/Dogs/23/Longeared/25/Somedog/76_ _/Insects/7/Spiders_ This is just an example and not what I'm going to use. My applications has nothing to do with animals. Is there a good way of doing this or should I use the standard routing instead?

    Read the article

  • RadUpload problem with firefox

    - by just_name
    Q: I use RadUpload Telerik control to upload more than image ..this control is flexible and amazing one.. it works perfectly but recently i find the following problem :: the problem appears only in firefox not IE when click on Select button in this control to select my file the button doesn't work at all ,,but when i click on the textbox(which the file path appear in)it opens the window which i can select a file from it .. i don't know what is the problem with firefox .. i wanna the default behavior to not confuse the user ,i wanna when clicking on Select button , showing a window to select my file from it like IE.. any suggestions to fix this problem please...

    Read the article

  • C# mvc 3 using selectlist with selected value in view

    - by Rob
    I'm working on a MVC3 web application. I want a list of categories shown when editing a blo from whe applications managements system. In my viewmodel i've got the following property defined for a list of selectlistitems for categories. /// <summary> /// The List of categories /// </summary> [Display(Name = "Categorie")] public IEnumerable<SelectListItem> Categories { get; set; } The next step, my controller contains the following edit action where the list of selectlistitems is filled from the database. public ActionResult Edit(Guid id) { var blogToEdit = _blogService.First(x => x.Id.Equals(id)); var listOfCategories = _categorieService.GetAll(); var selectList = listOfCategories.Select(x =>new SelectListItem{Text = x.Name, Value = x.Id.ToString(), Selected = x.Id.Equals(blogToEdit.Category.Id)}).ToList(); selectList.Insert(0, new SelectListItem{Text = Messages.SelectAnItem, Value = Messages.SelectAnItem}); var viewModel = new BlogModel { BlogId = blogToEdit.Id, Active = blogToEdit.Actief, Content = blogToEdit.Text, Title = blogToEdit.Titel, Categories = selectList //at this point i see the expected item being selected //Categories = new IEnumerable<SelectListItem>(listOfCategories, "Id", "Naam", blogToEdit.CategorieId) }; return View(viewModel); } When i set a breakpoint just before the view is being returned, i see that the selectlist is filled as i expected. So at this point everything seems to be okay. The viewmodel is filled entirely correct. Then in my view (i'm using Razor) i've got the following two rules which are supposed to render the selectlist for me. @Html.LabelFor(m => m.Categories) @Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId) @Html.ValidationMessageFor(m => m.Categories) When I run the code and open the view to edit my blog, I can see all the correct data. Also the selectlist is rendered correctly, but the item i want to be selected lost it's selection. How can this be? Until the point the viewmodel is being returned with the view everything is okay. But when i view the webpage in the browser, the selectlist is there only with out the correct selection. What am I missing here? Or doing wrong?

    Read the article

  • MVC routing problems - url generation

    - by roncansan
    Hi, I what to create a url that looks like website.com/sea/season/23/team Here is the MapRoute routes.MapRoute( "SeaTeam", "sea/season/{seasonId}/team/{action}/{name}", new { controller = "Team", action = "Index", name = UrlParameter.Optional} ); The Html.ActionLink looks like @Html.ActionLink("Add Team", "Index", "SeaTeam", new { seasonId = seasons.id }, null) But its generating the following url <a href="/SeaTeam?seasonId=1">Add Team</a> Any insights? Thanks...

    Read the article

  • some problems with jquery

    - by CoffeeCode
    I'm using AJAX_POSTUP. When i make a request it sends a file to a bowser [offers to download] (the files content are params of the action methods). Does anyone know whats going on and how i can avoid this problem??? i'm not aware of other plugins such as AJAX_POSTUP

    Read the article

  • JQuery code in ASP .NET content pages

    - by user2645830
    I have made a very simple sample project where I want to toggle an asp .net calendar control through jquery. Could anyone please point out why it is not working. I have made no changes to master page from the sample project provided for ASP .NET web application. <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication5._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> <script type="text/javascript" src="scripts/jquery-1.4.1.min.js"> </script> <script language="javascript" type="text/javascript"> // <![CDATA[ function Button1_onclick() { alert( $('<%=Calendar1.ClientID%>')); $('<%=Calendar1.ClientID%>').toggle(); } // ]]> </script> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Welcome to ASP.NET! </h2> <p> To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. </p> <input id="Button1" type="button" value="button" onclick="return Button1_onclick()" /> <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar> <p> You can also find <a href="http://go.microsoft.com/fwlink/? LinkID=152368&amp;clcid=0x409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. </p> </asp:Content>

    Read the article

  • Having all Views in the Shared folder - works but is throwing "caught exceptions". Performance conc

    - by Scott
    Hi everyone, I have a simple but heavily used app done in VS2010/MVC2. I didn't like having separate folders for each view/controller and so have all the views in the Shared folder. It's working fine but while debugging in VS, I noticed that it's throwing IO "caught exceptions" since it seems to be looking in the [FolderName]/[ViewName] folder before going down to the Shared folder. Again, the app runs fine but I'm concerned that all these "caught exceptions" will have a minor performance impact since they do have a cost in via the CLR. Is there any way I can configure the Routing so that it will only look in the Shared folder? Thanks.

    Read the article

  • Similar route mapping

    - by Denis Agarev
    I need to map to create controller what must response to two urls: "http://localhost/api/controller?id=1" (where only id value can change) "http://localhost/api/controller/anotherId/someconst" (where anotherId is the only one changing part) i map it to such route: routes.MapHttpRoute("Test", "api/{controller}/{id}/{someconst}", new { controller = "Test", someconst = RouteParameter.Optional }); And have to methods in my controller: public void Get(int id) { ... } public void Get(int anotherId, string someconst ) { ... } It works...But it doesn't look nice...cause "string someconst" is not a param, it's just a const part of url. But if i remove "string someconst" param second url wouldn't work. Is it possible to map one controller to two routes to resolve this urls to make it clear without fake param which is a const in fact?

    Read the article

  • What Controller/Action will this go to?

    - by rkrauter
    Assume this is the first route entry: routes.MapRoute( "myRoute", "employees/{city}/{pageNumber}", new { controller="Employees", action = "List", pageNumber = 1 } ); If I make the following request employees/london/2 it gets matched to the following action method: public ActionResult List(string city) {} How did that happen? I did not specify "city" in my object defaults: new { controller="Employees", action = "List", pageNumber = 1 } Please explain. Thanks!

    Read the article

  • Using POST or SESSION to capture data

    - by Karinne
    Hi all! I'm currently working on web application using VB in ASP.NET. Right now I have 1 page with panels that we are using to show/hide depending on the flow. When the user first comes in, he/she is presented with a gridview containing a list of clients. Then the user, clicks a link from a row and is presented a form where he/she can update the clients' info. Originally, I had a HYPERLINKFIELD that put the clientId in the url, then I'd grab the url and do the code appropriately <asp:HyperLinkField Text='<%$ Resources:Resource, ManageClient %>' DataNavigateUrlFields="CLIENT_ID" DataNavigateUrlFormatString="~/clients/manage.aspx?clientId={0}" /> Now, I'm rethinking that and wondering if it's better to use SESSIONs to grab the clientID via this instead <asp:TemplateField Visible="false"><ItemTemplate><asp:Label runat="server" ID="hidClientId" Text='<%# Bind("CLIENT_ID")%>' Visible="false" /></ItemTemplate></asp:TemplateField> <asp:ButtonField Text='<%$ Resources:Resource, ManageClient %>' CommandName="Manage" /> Or use the POST method, which I'm not sure how it works in .NET (but I've used it in PHP) Any help would be greatly appreciated.

    Read the article

  • Proxy object references in MVC code

    - by krystan honour
    Hi there, I am just figuring out best practice with MVC now I have a project where we have chosen to use it in anger. My question is. If creating a list view which is bound to an IEnumerable is this bad practise? Would it be better to seperate the code generated by the WCF Service reference into a datastructure which essentially holds the same data but abstracts further from the service, meaning that the UI is totally unaware of the service implementation beneath. or do people just bind to the proxy object types and have done with it ? My personal feeling is to create an abstraction but this seems to violate the DRY principle.

    Read the article

  • How to show ModelState.AddModelError when the Model is Empty in MVC4

    - by kk1076
    I am displaying a shopping cart. I need to check for empty values in Shopping cart and display a message like "The Shopping Cart is empty". When I use ModelState.AddModelError in myAction, it throws an exception as there is null reference in Model. How to display the ErrorMessage. My Action public ActionResult Index() { string id = Request.QueryString["UserID"]; IList<CartModel> objshop = new List<CartModel>(); objshop = GetCartDetails(id); if (objshop.Count > 0) { return View(objshop.ToList()); } else { ModelState.AddModelError("", "Your Shopping Cart is empty!"); } return View(); } My View @{ @Html.ValidationSummary(true) } <th > @Html.DisplayNameFor(model => model.ProductName) </th> <th > @Html.DisplayNameFor(model => model.Quantity) </th> <th > @Html.DisplayNameFor(model => model.Rate) </th> <th > @Html.DisplayNameFor(model => model.Price) </th> @foreach (var item in Model) { <td> @Html.DisplayFor(modelItem => item.ProductName)</td> <td> @Html.DisplayFor(modelItem => item.Quantity)</td> <td> @Html.DisplayFor(modelItem => item.Rate) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> } Any suggestions.

    Read the article

  • Is My DataTable Snippet Written Correctly?

    - by user311509
    public static DataTable GetDataTable(SqlCommand sqlCmd) { DataTable tblMyTable = new DataTable(); DataSet myDataSet = new DataSet(); try { //1. Create connection mSqlConnection = new SqlConnection(mStrConnection); //2. Open connection mSqlConnection.Open(); mSqlCommand = new SqlCommand(); mSqlCommand = sqlCmd; //3. Assign Connection mSqlCommand.Connection = mSqlConnection; //4. Create/Set DataAdapter mSqlDataAdapter = new SqlDataAdapter(); mSqlDataAdapter.SelectCommand = mSqlCommand; //5. Populate DataSet mSqlDataAdapter.Fill(myDataSet, "DataSet"); tblMyTable = myDataSet.Tables[0]; } catch (Exception ex) { } finally { //6. Clear objects if ((mSqlDataAdapter != null)) { mSqlDataAdapter.Dispose(); } if ((mSqlCommand != null)) { mSqlCommand.Dispose(); } if ((mSqlConnection != null)) { mSqlConnection.Close(); mSqlConnection.Dispose(); } } //7. Return DataSet return tblMyTable; } I use the above code to return records from database. The above snippet would run in web application which expected to have around 5000 visitors daily. The records returned reach 20,000 or over. The returned records are viewed (read-only) in paged GridView. Would it be better to use DataReader instead of DataTable? NOTE: two columns in the GridView are hyperlinked.

    Read the article

  • Is C# WebAPI worth it? Can I use standart MVC4 to create my API?

    - by Steve
    I need to build a massive API and I'm trying out WebAPI instead of default MVC4 projects and it seems that it just makes things more difficult. Can have only 4 methods in controller Get, Post, Put, Delete, if I want more I need to modify route for that particular method FluentValidation won't work with WebAPI so I need to use DataAnnotations which I really don't want to. Can't use dynamic return data-types My question is: Would it really be that bad if I would use MVC4 project and use default ActionResults that return Json? What are real advantages of using WebAPI, why did they even made them in the first place if you can easily convert your project to API?

    Read the article

  • MVC4 Model in View has nested data - cannot get data in model

    - by Taersious
    I have a Model defined that gets me a View with a list of RadioButtons, per IEnumerable. Within that Model, I want to display a list of checkboxes that will vary based on the item selected. Finally, there will be a Textarea in the same view once the user has selected from the available checkboxes, with some dynamic text there based on the CheckBoxes that are selected. What we should end up with is a Table-per-hierarchy. The layout is such that the RadioButtonList is in the first table cell, the CheckBoxList is in the middle table cell, and the Textarea is ini the right table cell. If anyone can guide me to what my model-view should be to achieve this result, I'll be most pleased... Here are my codes: // // View Model for implementing radio button list public class RadioButtonViewModel { // objects public List<RadioButtonItem> RadioButtonList { get; set; } public string SelectedRadioButton { get; set; } } // // Object for handling each radio button public class RadioButtonItem { // this object public string Name { get; set; } public bool Selected { get; set; } public int ObjectId { get; set; } // columns public virtual IEnumerable<CheckBoxItem> CheckBoxItems { get; set; } } // // Object for handling each checkbox public class CheckBoxViewModel { public List<CheckBoxItem> CheckBoxList { get; set; } } // // Object for handling each check box public class CheckBoxItem { public string Name { get; set; } public bool Selected { get; set; } public int ObjectId { get; set; } public virtual RadioButtonItem RadioButtonItem { get; set; } } and the view @model IEnumerable<EF_Utility.Models.RadioButtonItem> @{ ViewBag.Title = "Connect"; ViewBag.Selected = Request["name"] != null ? Request["name"].ToString() : ""; } @using (Html.BeginForm("Objects" , "Home", FormMethod.Post) ){ @Html.ValidationSummary(true) <table> <tbody> <tr> <td style="border: 1px solid grey; vertical-align:top;"> <table> <tbody> <tr> <th style="text-align:left; width: 50px;">Select</th> <th style="text-align:left;">View or Table Name</th> </tr> @{ foreach (EF_Utility.Models.RadioButtonItem item in @Model ) { <tr> <td> @Html.RadioButton("RadioButtonViewModel.SelectedRadioButton", item.Name, ViewBag.Selected == item.Name ? true : item.Selected, new { @onclick = "this.form.action='/Home/Connect?name=" + item.Name + "'; this.form.submit(); " }) </td> <td> @Html.DisplayFor(i => item.Name) </td> </tr> } } </tbody> </table> </td> <td style="border: 1px solid grey; width: 220px; vertical-align:top; @(ViewBag.Selected == "" ? "display:none;" : "")"> <table> <tbody> <tr> <th>Column </th> </tr> <tr> <td><!-- checkboxes will go here --> </td> </tr> </tbody> </table> </td> <td style="border: 1px solid grey; vertical-align:top; @(ViewBag.Selected == "" ? "display:none;" : "")"> <textarea name="output" id="output" rows="24" cols="48"></textarea> </td> </tr> </tbody> </table> } and the relevant controller public ActionResult Connect() { /* TEST SESSION FIRST*/ if( Session["connstr"] == null) return RedirectToAction("Index"); else { ViewBag.Message = ""; ViewBag.ConnectionString = Server.UrlDecode( Session["connstr"].ToString() ); ViewBag.Server = ParseConnectionString( ViewBag.ConnectionString, "Data Source" ); ViewBag.Database = ParseConnectionString( ViewBag.ConnectionString, "Initial Catalog" ); using( var db = new SysDbContext(ViewBag.ConnectionString)) { var objects = db.Set<SqlObject>().ToArray(); var model = objects .Select( o => new RadioButtonItem { Name = o.Name, Selected = false, ObjectId = o.Object_Id, CheckBoxItems = Enumerable.Empty<EF_Utility.Models.CheckBoxItem>() } ) .OrderBy( rb => rb.Name ); return View( model ); } } } What I am missing it seems, is the code in my Connect() method that will bring the data context forward; at that point, it should be fairly straight-forward to set up the Html for the View. EDIT ** So I am going to need to bind the RadioButtonItem to the view with something like the following, except my CheckBoxList will NOT be an empty set. // // POST: /Home/Connect/ [HttpPost] public ActionResult Connect( RadioButtonItem rbl ) { /* TEST SESSION FIRST*/ if ( Session["connstr"] == null ) return RedirectToAction( "Index" ); else { ViewBag.Message = ""; ViewBag.ConnectionString = Server.UrlDecode( Session["connstr"].ToString() ); ViewBag.Server = ParseConnectionString( ViewBag.ConnectionString, "Data Source" ); ViewBag.Database = ParseConnectionString( ViewBag.ConnectionString, "Initial Catalog" ); using ( var db = new SysDbContext( ViewBag.ConnectionString ) ) { var objects = db.Set<SqlObject>().ToArray(); var model = objects .Select( o => new RadioButtonItem { Name = o.Name, Selected = false, ObjectId = o.Object_Id, CheckBoxItems = Enumerable.Empty<EF_Utility.Models.CheckBoxItem>() } ) .OrderBy( rb => rb.Name ); return View( model ); } } }

    Read the article

< Previous Page | 85 86 87 88 89 90 91 92 93 94 95 96  | Next Page >