Display data on form and update form asynchronously - c#

What is the best way to approaching this? I have a text box where Teachers enter Student ID and I want to display student information based on the id entered. Once the student info is displayed, I have a drop down list which populates with a list which lists all the classes that student is enrolled in. Once a course is selected from that drop down list I want to display students progress on the form in a particular section on the form. How can I approach this? Here is What I have so far:
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Student.Models;
namespace Student.Controllers
{
public class StudentFormController : Controller
{
//
// GET: /StudentForm/
public ActionResult Index()
{
return View("StudentForm");
}
public ActionResult DisplayStudentDetails(string StudentId)
{
StudentDataContext db = new StudentDataContext();
var StudentName = (from p in db.vwStudent.Where(a => a.StudentID == StudentId)
group p by p.StudentName into g
select g.Key).FirstOrDefault();
var StudentClassList = (from p in db.vwStudent.Where(a => a.StudentID == StudentId)
group p by p.ClassID into g
select g.Key).ToList();
ViewData["StudentName"] = StudentName;
ViewData["StudentClassList "] = StudentClassList ;
return View("StudentForm");
}
public ActionResult DisplayClassDetails(string StudentId, string ClassId)
{
StudentDataContext db = new StudentDataContext();
ViewData.Model = (from p in db.vwStudentProgress.Where(a => a.StudentID == StudentId && a.ClassID == ClassId);
return View("LPForm");
}
}
}
View(Form):
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content3" ContentPlaceHolderID="TitleContent" runat="server">
Student Form
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="MainContent" runat="server">
<form id="form2" method="get" action="/StudentForm/DisplayStudentDetails/" runat="server">
<div style="text-align: left; height: 202px;">
<asp:ScriptManager ID="ScriptManager2" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
Student Id:<input type="text" name="id" value="<%=HttpContext.Current.Request.QueryString["StudentId"]%>" /><br />
Student Name:<input type="text" name="StudentName" value="<%=ViewData["ShortName"]%>" /><br />
Classes Enrolled in:
<select name="Classes">
<%if (ViewData["Classes"] != null)
{%>
<% foreach (int? Classes in (List<int?>)ViewData["Classes"])
{%>
<option><%=Classes%></option>
<%}%>
<%}%>
</ContentTemplate>
</asp:UpdatePanel>
<input type="submit" value="Display Student Details"/>
</div>
</form>
</asp:Content>

What is the best way to approaching this?
Simple answer is AJAX. Don't try to use update panels in an ASP.NET MVC application. Use jquery to male ajax calls and update portions of your page.
Once a course is selected from that drop down list I want to display
students progress on the form in a particular section on the form. How
can I approach this?
Basically you should bind to the change event of the dropdown through jquery and call an action that returns a partial view.
Use html helpers to create textboxes, form and other stuff and avoid using the html elements directly.

Related

ASP.NET Web Forms: How can I pass a list to a user control?

My website has categories of posts (e.g. longreads, FAQs).
I am trying to display a list of links to category pages twice: in the header and in the footer.
So I have made a CategoryList : UserControl with a public List<Category>.
CategoryList.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="CategoryList.ascx.cs" Inherits="WebApp.Controls.CategoryList" %>
<% foreach (WebApp.Data.Category c in Categories) // .CategoriesList.Categories.get returned null
{ %>
<span>
<a href="<%= GetRouteUrl("category-view", new { category = c.CategorySlug }) %>">
<%= c.CategoryName %>
</a> <!-- e.g. Longreads -->
</span>
<% } %>
CategoryList.ascx.cs:
using System;
using System.Collections.Generic;
namespace WebApp.Controls
{
public partial class CategoryList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e) { }
public List<Data.Category> Categories { get; set; }
}
}
On the master page codebehind MainMaster.Master.cs I also have a List<Category> that is set during initialization like
public List<Category> Categories { get; } = Data.Categories.All.ToList();
Now in MainMaster.Master I try to display this control passing the list to it with an inline data-binding expression:
<%# Register TagPrefix="custom" TagName="CategoryList" Src="~/Controls/CategoryList.ascx" %>
<!-- HTML form opening -->
<custom:CategoryList Categories="<%# Categories %>" runat="server" />
<!-- HTML form closing -->
When I run this I get a NullReferenceException in CategoryList.ascx on the line
foreach (WebApp.Data.Category c in Categories) // .CategoriesList.Categories.get returned null
Although when I try to do the same foreach loop on the page MainMaster.Master itself it works alright:
<!-- HTML form opening -->
<% foreach (WebApp.Data.Category c in Categories) // MainMaster.Categories
{ %>
<span>
<a href="<%= GetRouteUrl("category-view", new { category = c.CategorySlug }) %>">
<%= c.CategoryName %>
</a>
</span>
<% } %>
<!-- HTML form closing -->
But I wouldn't like to repeat exactly the same code twice.
Is there a proper way I can pass a list to a user control?
Try assigning your categories in code behind, give the control an Id then reference it directly:
<custom:CategoryList runat="server" id="categoryList" />
You should be able to access it in your master page code behind:
categoryList.Categories = Data.Categories.All.ToList();
You will have to make sure depending on where you put this code, that your events fire in the correct order.

LIKE in "where" LINQ statement causes error [duplicate]

This question already has answers here:
How to use SQL 'LIKE' with LINQ to Entities? [duplicate]
(11 answers)
Linq LIKE functionality
(1 answer)
Closed 7 years ago.
ProductModel.cs: (class)
public List<Product> GetSearchedProduct (string Name)
{
try
{
using (garagedbEntities db = new garagedbEntities())
{
List<Product> products = (from x in db.Products
where x.Name LIKE #txtSearch
select x).ToList();
return products;
}
}
catch (Exception)
{
return null;
}
}
search.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Button" OnClick="btnSearch_Click" />
<br />
<asp:Panel ID="pnlProducts" runat="server">
<br />
</asp:Panel>
<div style="clear:both"></div>
This is my search.aspx file. Actually I want to get the name of the product from TextBox then pass it to method which retrieves the products.
In linq you should use Contains:
List<Product> products = (from x in db.Products
where x.Name.Contains(Name)
select x).ToList();
Edit: To use method you should create a new instance of ProductModel and then call the GetSearchedProduct method and send the txtSearch as a parameter to it. Like this:
protected void btnSearch_OnClick(object sender, EventArgs e)
{
ProductModel pr = new ProductModel();
var result = pr.GetSearchedProduct(txtSearch.Text);
}

Load DropDownList from ViewData in MVC 2

I have the following View. This is the whole code of my view
<asp:Content ID="Content2" ContentPlaceHolderID="HeadContent" runat="server">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div>
<table>
<tr>
<td>
<select id="clientDDL">
</select>
<% Html.DropDownList("clientDDL",
new SelectList((IEnumerable)ViewData["Clients"], "Code", "Name")); %>
</td>
</tr>
</table>
</div>
</asp:Content>
I use the next ViewData from my Model:
public static List<lookup> GetClients()
{
using (ModelDataContext data = new ModelDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
{
List<lookup> retVal = new List<lookup>();
List<Client> lClient = data.Clients.Where(a => a.IsActive == true).ToList();
lClient = lClient.OrderBy(o => o.ClientName).ToList();
foreach (Client item in lClient)
{
retVal.Add(new lookup() { Code = item.ClientID.ToString(), Name = item.ClientName, });
}
return retVal;
}
}
This is my Controller:
public ActionResult ProcedureFilter()
{
ViewData["Clients"] = WorkflowModels.GetClients();
return View();
}
What did I miss? My DropDownList is still empty. Maybe i have to put some reference? Any suggestions please.
UPDATE:
The problem was ';' at the end of part <%= %>. The works code:
<%= Html.DropDownList("clientDDL",
new SelectList((IEnumerable)ViewData["Clients"], "Code", "Name")) %>
In the ASP.NET code you provided, 2 HTML select tags (or DropdownLists) are defined with the same id (cliendDDL) :
<select id="clientDDL"> <-- the first one
</select>
<% Html.DropDownList("clientDDL",
new SelectList((IEnumerable)ViewData["Clients"], "Code", "Name")); %> <-- the second one, Html.DropDownList generating a select under the hood.
Would it be possible that only the first one is displayed (the empty one) and the second remains hidden because of a missing character, changing your expected HTML generation routine (Html.DropDownList) into an Embedded Code Block?
Maybe instead of :
<% Html.DropDownList
it should be :
<%= Html.DropDownList or <%: Html.DropDownList
See here for <%:%> ASP.NET 4 syntax
Edited
Also the ";" end of line character is not needed and should be removed.
View Page:
"<%=Html.DropDownList("Description", New SelectList(ViewData("Description")), "--Select--")%>"
Contoller:
Function Purchase() As ActionResult:
Dim dataContext As New tblMVCDataContext
Dim teststr As String
Dim itemVar = From U In dataContext.Items Select U.Description
For Each tbItem In itemVar
teststr += tbItem + ","
Next
ViewData("Description") = teststr.Split(",")
Return View(itemVar)
End Function

How to get edited value in MVC

im new in MVC 1.
In my project im assigning IList to model and using forloop im assigning to Textbox , dropdox etc... User can change the value as per there requirement. What i want, how i will get the value present on aspx page in the form of ILIST when user click on SAVE ALL button present at the top of the page.
here are the code which im using for populating form....
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm("MyController", "EditCopyRestaurantMealRate", FormMethod.Post, new { id = "frmEditCopyRestaurantMealRate" }))
{ %>
<%= Html.Submit("Save All Services", ApplicationPermissions.ManageContract, new { name = "submitButton" })%>
<table width="100%" class="edit_restaurant_form">
<col width="19%" />
<col width="30%" />
<col width="19%" />
<col width="*" />
foreach (var item in Model)
{
%>
<tr>
<th>
<label for="DateFrom">
Effective from:</label> <label class="mandatory">* </label>
</th>
<td>
<% string dtFrom = "";
dtFrom = item.Datefrom.ToString("dd-MMM-yyyy");
%>
<%= Html.TextBox("DateFrom", dtFrom)%>
</td>
<th>
<label for="DateTo">
Effective to:</label> <label class="mandatory">* </label>
</th>
<td>
<% string dtTo = "";
dtTo = item.Dateto.ToString("dd-MMM-yyyy");
%>
<%= Html.TextBox("DateTo", dtTo)%>
</td>
</tr>
<% }
%>
here is the controller code.
public ActionResult MyController(string submitButton, IList<CMS.Model.VcmsRestaurant> AddendumMealRates)
{
// Need to receiv all value in list which is edited
return View(#"~\index.aspx", AddendumMealRates);
}
How I will get the the value in MyController which user will edited on the page?
You create a method in the controller, that will catch the postback.
If it's simple data you can do something like:
public ActionResult EditRestaurant(string dateFrom, string dateTo)
{
// do something with the values here.
}
Or Create a viewmodel, that can encapsulate more complex data:
public ActionResult EditRestaurant(EditRestaurantViewModel editRestaurantVM)
{
// do something with the values here.
}
As I can see that you are trying to postback a list of items, in a table, I'll add this to my answer:
As far as I know, you can't easily post that structure of data back, you will either need to use a javascript library like Knockout.js, or use raw javascript/jquery to gather the data, and send it back by AJAX.
Here i found the ans.
public ActionResult EditRestaurant(IList<string> dateFrom, IList<string> dateTo)
{
// do something with the values here.
}

View loop value doesn't change after first value

I have an ICollection<String> being passed to my view and I do a foreach to load a partial view. It loops through the correct number of times, however, the value it passes is the same and I know in the model that this is not the case.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index", new List<String>());
}
[HttpPost]
public ActionResult Index(List<String> txtValue)
{
return View("Index", txtValue);
}
}
View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<String>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
//Deletes the div the Control is in.
$(".delete").live("click", function () {
$(this).parent().remove();
});
//Adds the TextBoxes to divControls
function AddTextBox(Value) {
var elements = "<div><input name=\"txtValue\" type=\"text\" /><input type=\"button\" class=\"delete\" value=\"-\" /><br/></div>";
$("#divControls").append(elements);
}
</script>
<h2>Controls!!!</h2>
<input id="btnAdd" type="button" name="Refresh" value="+" onclick="AddTextBox()" />
<% using (Html.BeginForm())
{ %>
<input id="btnsubmit" type="submit" name="Submit" onclick="Submit" />
<div id="divControls">
<%
foreach (var text in this.Model)
{ %>
<%=Html.TextBox("txtValue", text, new { id = "Value", name = "txtValue" })%>
<% Html.RenderPartial("TextControl", text);
}
%>
</div>
<%
}
%>
</asp:Content>
TextControl.ascx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>
<div>
<%=Html.TextBox("txtValue", this.Model, new { id = "Value", name = "txtValue" }) %>
<input id="btn" type="button" class="delete" value="-" /><br/>
</div>
The values of the model passed from the controller to the view are correct, even when passed to the user control "TextControl" the value is correct, but when the Textbox displays they are all just the first value of the original model passed in.
Ex.
Model as List<String> { "1", "2", "3", "4" }
passed to the view, will iterate through each one correctly, passing the correct string to "TextControl" to create a Html.TextBox("name", this.Model). Everything on the debugging side appears correct, however, when it finishes all the textboxes are "1" (or the first value in the list).
Here's a link to my exact code: http://www.sendspace.com/file/sypl1u
Note:
I came up with a solution of just using <input type="text" name="txtValue" value="<%= this.Model %>" /> instead.
Potential issue: you are using ElementAt which is LINQ method that fave special behavior for IList argument, but you are passing in txtValue as result of some query. In this case ElementAt may case sequence to be enumerated multiple times and may even fail if sequence can't be re-enumerated.
Consider simple foreach on the collection instead:
foreach (var text in Model)
{
Html.RenderPartial("TextControl", text);
}

Categories