.Net MVC 4. Ajax - ajax

I want to search result from db andy show on same view using ajax but it is not happening. Here is my Index page where I defined the Search box and a table to show search result.
Index View is
#{
Layout = null;
}
#model IEnumerable<BR.Models.PostJob>
#using (Ajax.BeginForm("AjaxSearch", "Student",
new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" }))
{
<input type="text" name="q" />
<input type="submit" value="Search" />
}
My Table to show Searched result is.
<table id="searchResults">
</table>
My Controller Function is.
public PartialViewResult AjaxSearch(string q)
{
SqlDataReader dr;
SqlConnection con = new SqlConnection("Data Source=IT-INTERN3;Initial Catalog=bridging_the_gap;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "select * from Jobs where job_title ='" + q + "'";
cmd.Connection = con;
var r = cmd.ExecuteReader();
return this.PartialView(r);
}
My Partial View is
#model IEnumerable<BR.Models.PostJob>
<table>
<tr>
<th>
id
</th>
<th>
job_title
</th>
<th>
job_description
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#item.id
</td>
<td>
#item.job_title
</td>
<td>
item.job_description
</td>
</tr>
}
</table>
On click of search button it is going to AjaxSearch function but not showing result in Index view.

You must map ExecuteReader result to object(PostJob).
In AjaxSearch action replace this line
var r = cmd.ExecuteReader();
with
List<PostJob> results = new List<PostJob>();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.Read())
{
PostJob newItem = new PostJob();
newItem.id = dr.GetInt32(0); // 0 is id column order
newItem.job_title = dr.GetString(1); // 1 is job_title column order
newItem.job_description = dr.GetString(2);
results.Add(newItem);
}
}
return PartialView(results);

Related

how to dynamically edit the bind data in sql using mvc3 web grid

i am new to mvc.. i have a task that, i have to bind data from existing table in sql using asp.net mvc3(Razor) Web Grid .. now i have to edit the data in webGrid.. i dont know how the edit operation is going to made... Plzz Help me out...
i have given my bind data.. plz let me know how to edit it...
Controller:
public ActionResult Index()
{
var list = GetList();
return View(list);
}
public List<Teacher> GetList()
{
var modelList = new List<Teacher>();
using (SqlConnection conn = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Demo;Data Source=CIPL41\SQLEXPRESS"))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("Select T_Id,T_Name,T_Address,Sub_Id from teacher", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new Teacher();
model.T_Id = Convert.ToInt32(ds.Tables[0].Rows[i]["T_Id"]);
model.T_Name = ds.Tables[0].Rows[i]["T_Name"].ToString();
model.T_Address = ds.Tables[0].Rows[i]["T_Address"].ToString();
model.Sub_Id = ds.Tables[0].Rows[i]["Sub_Id"].ToString();
modelList.Add(model);
}
}
return modelList;
}
//
Index.cshtml
#model IEnumerable<MvcApplication1.Models.Teacher>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Index", "Teacher"))
{
<table>
<tr>
<th></th>
<th>
T_Id
</th>
<th>
T_Name
</th>
<th>
T_Address
</th>
<th>
Sub_Id
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.T_Id }) |
#* #Html.ActionLink("Details", "Details", new { id=item.T_Id }) |*#
#Html.ActionLink("Delete", "Delete", new { id=item.T_Id })
</td>
<td>
#Html.TextBox("T_Id", item.T_Id , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("T_Name", item.T_Name , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("T_Address", item.T_Address , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("Sub_Id",item.Sub_Id,new { #style = "width:100px;"})
</td>
</tr>
}
</table>
Plz help me out....
Have a look at this tutorial http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/examining-the-edit-methods-and-edit-view
I think it explains exactly what you're trying to do.

ASP.NET MVC 3 - Partial View displayling as new page

I have had look at a few post already here but I am none the wiser. I tried my first example of Ajax but to no avail. The Partial View is loaded into a separate page as opposed to changing the dom element in the current page.
The pupose is by clicking on the Refresh link in updates the "Last Activity Date" value of the current row only.
Please if there is an easy well of doing this can you also let me know?
View:
#model IEnumerable<RegistrationManager.User>
#{
ViewBag.Title = "Users";
}
#section scripts {
#Content.Script(Url, "jquery-unobtrusive-ajax.min.js")
}
<h2>Users</h2>
<table>
<tr>
<th>Email Address</th>
<th>Given Names</th>
<th>Surname</th>
<th>Last Activity Date</th>
<th>Refresh</th>
</tr>
#foreach (var item in Model)
{
string selectedRow = "";
if (ViewBag.UserId != null && item.UserId == ViewBag.UserId)
{
selectedRow = "selectedrow";
}
<tr class="#selectedRow" valign="top">
<td>
#item.UserName
</td>
<td>
#item.Profile.GivenNames
</td>
<td>
#item.Profile.Surname
</td>
<td>
<div id="#String.Format("LastActivityDate{0}", item.UserId)">#Html.Partial("_DateOnlyPartialView", item.LastActivityDate)</div>
</td>
<td>
#Ajax.ActionLink("Refresh", "Refresh",
new { UserId = item.UserId },
new AjaxOptions {
UpdateTargetId = "LastActivityDate" + item.UserId,
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
</td>
</tr>
}
</table>
Conrtoller:
public PartialViewResult Refresh(Guid? UserId)
{
User user = _db.Users.Find(UserId);
user.RefreshLastActivityDate();
return PartialView("_DateOnlyPartialView", user.LastActivityDate);
}
Have you included/referenced all the necessary javascript files?
If you have UnobtrusiveJavaScriptEnabled then you'll need:
jQuery
jquery.unobtrusive-ajax.js
if you also use client side validation, you'll need;
jquery.validate.js
jquery.validate.unobtrusive.js
These files can all be found when you create a new MVC3 project.

binding dropdownlist by another dropdownlist in mvc 3

I'm new with mvc and I have 2 dropdownlists and I need to bind second one by first one using mvc 3..
Code sample
#<table>
<tr>
<td>
#Html.DropDownList("Brands", Model.Brands, "Select Brand", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Models", Model.Models, "Select Model", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Devices", Model.Devices, "Select Device", New With {.style = "width:150px;"})
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Systems", Model.Systems, "Select System", New With {.style = "width:150px;"})
</td>
</tr>
</table>
I need to fill Models by Brands and Fill Devices by Models.
any help please..
Thanks
In view:
#Html.DropDownListFor( x => x.Model, new SelectList( LookupUtils.GetModelsList(Model.Brand), "Value", "Text", Model.Model))
LookupUtils is a static class have:
public static List<SelectListItem> GetModelsList(int brand)
{
var dataContext = new YourDataContext( );
var data = dataContext.GetModelsFn(brand).ToList();
var result = ( from res in data
select new SelectListItem()
{
Text = res.modelName,
Value = res.modelId.ToString()
} ).ToList();
return result;
}
For dynamicly update some dropdown lists, you should use jQuery-Collapse plugin: http://github.com/danielstocks/jQuery-Collapse/

How to bind data to Grid in MVC3?

For past few days I had been working with MVC...
I have to show a bunch of data in a grid...these all days I managed to show it in a table but my requirement is to bind it to jquery grid or Webgrid...
I am stuck with this I don't know how to do this expecting ideas and suggestions....
Controller
public ActionResult Index()
{
var bugList = GetList();
return View(bugList);
}
public List<ProjectModel> GetList()
{
var modelList = new List<ProjectModel>();
using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("Select * from Projects", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new ProjectModel();
model.ID = Convert.ToInt16(ds.Tables[0].Rows[i]["ProjectID"]);
model.projectName = ds.Tables[0].Rows[i]["projectName"].ToString();
model.Description = ds.Tables[0].Rows[i]["Description"].ToString();
model.status = ds.Tables[0].Rows[i]["Status"].ToString();
modelList.Add(model);
}
}
return modelList;
}
View (ASPX)
<table>
<thead align="center">
<tr class="BoldCenterAlignHeaderStyle">
<th>
ProjectName
</th>
<th>
Status
</th>
<th align="center">
Edit
</th>
</tr>
</thead>
<% foreach (var item in Model) { %>
<tr>
<td>
<%:Html.LabelForModel(item.projectName) %>
</td>
<td>
<%:Html.LabelForModel(item.status) %>
</td>
<td align="center">
<img src="../../Content/edit.gif" height="8px"/>
<%--<%:Html.ActionLink("Edit", "Edit", new { id = item.ID })%> --%>
<%-- <img src="../../Content/delete.gif" height="8px" />--%>
</td>
</tr>
<%} %>
if i can do paging in a table how can i do that or else how should i display he data in a grid can any one help me please....can any one explain me how to do this
Example for webgrid:
#model IEnumerable<ProjectModel>
#{
var grid = new WebGrid(
source: Model,
rowsPerPage: 4);
}
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "header",
rowStyle: "row",
footerStyle: "footer",
alternatingRowStyle: "altRow",
columns: grid.Columns (
grid.Column("projectName"),
grid.Column("ProjectID")
))
You can use Webgrid for this.
Here are few links for understanding how webgrid works
Introduction to webgrid
http://www.mikesdotnetting.com/Article/154/Looking-At-The-WebMatrix-WebGrid
http://msdn.microsoft.com/en-us/magazine/hh288075.aspx
Paging in webgrid
http://yassershaikh.com/webgrid-paging-with-pager-method-in-razor-mvc/
Advanced (Efficient) Paging in Webgrid
http://www.dotnetcurry.com/ShowArticle.aspx?ID=615
Hope this helps..!

Parameters from view not getting to controller action method

I'm implementing Troy Goode's PagedList in one of my views (ASP.NET MVC 3 Razor). The challenge I'm having is when I click on a page number link, the request is routed to my HttpGet method, which just returns the empty page (ready for input).
My View Model:
public class SearchViewModel
{
public SelectList IndustrySelectList { get; set; }
public IPagedList<KeyValuePair<string, SearchResult>> SearchResults { get; set; }
public PagingInfo PagingInfo { get; set; }
}
Controller:
[HttpGet]
public ViewResult Search(string searchTerm = "")
{
SearchViewModel vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName"),
PagingInfo = new PagingInfo
{
CurrentPage = 1,
ItemsPerPage = 25,
TotalItems = 0
}
};
return View(vm);
}
[HttpPost]
public ActionResult Search(string[] industries, string searchTerm = "", int page = 1)
{
SearchViewModel vm = null;
_url = "http://localhost/MasterNode/masternode.cgi?zoom_query={" + searchTerm + "}&zoom_xml=1&zoom_page={startPage?}&zoom_per_page=1000";
StringBuilder sb = new StringBuilder();
int pageSize = 5;
if (string.IsNullOrEmpty(searchTerm))
{
vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName")
};
}
else
{
_request = new SearchRequest(SearchRequest.EnvironmentTypes.Development, "", _url, searchTerm, SearchRequest.SearchType.AllWords, 1000);
sb.Append(GetResults(_url));
_results = new Dictionary<string, SearchResult>();
ParseResults(sb);
GetDetailInformationForResults(searchTerm);
vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName"),
SearchResults = _results.ToList<KeyValuePair<string, SearchResult>>().ToPagedList(1, 25),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = pageSize,
TotalItems = _results.Count()
}
};
}
return View(vm);
}
View:
#model MultiView.OmniGuide.ViewModels.SearchViewModel
#using MultiView.OmniGuide.HtmlHelpers
#using PagedList
#using PagedList.Mvc
#{
ViewBag.Title = "Search";
}
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("Search", "Home"))
{
#Html.HiddenFor(c => c.IndustrySelectList)
#Html.HiddenFor(c => c.PagingInfo)
#Html.HiddenFor(c => c.SearchResults)
<table width="70%">
<tr>
<td colspan="2" style="background: #fff">
<input id="searchTerm" name="searchTerm" type="text" class="SearchBox" style="width: 450px" />
<input type="submit" class="SearchButton" value=" " />
</td>
</tr>
<tr align="left">
<td align="left" style="background: #fff">
#Html.ActionLink("MultiView corporate site", "Search")
</td>
</tr>
<tr>
<td colspan="1" align="center" style="width: 450px">
#{
Html.Telerik().PanelBar()
.Name("searchPanel")
.Items(title =>
{
title.Add()
.Text("Filter by Industry")
.Content(() =>
{
#Html.RenderPartial("_Industry", #Model);
});
})
.Render();
}
</td>
</tr>
<tr><td colspan="2"></td></tr>
</table>
<br />
if (Model.SearchResults != null)
{
<table width="70%">
<tr>
<th>
Company Image
</th>
<th class="tableHeader">
Company Name Here
</th>
<th class="tableHeader">
Website
</th>
</tr>
#foreach (KeyValuePair<string, MultiView.OmniGuide.Models.SearchResult> itm in Model.SearchResults)
{
<tr>
<td align="left" style="width: 15%">
#itm.Value.DetailedInfo.LogoURL
</td>
<td align="left" style="width: 60%">
<p style="text-align: left">
#itm.Value.DetailedInfo.DescriptionAbbreviated
<br />
</p>
#Html.AnchorLink(itm.Value.FoundURL, itm.Value.FoundURL)
</td>
<td style="width: 25%">
#itm.Value.FoundURL
</td>
</tr>
}
</table>
#Html.PagedListPager((IPagedList)Model.SearchResults, page => Url.Action("Search", "Home", new { page }))
}
}
When text is supplied in the input box and the button is clicked, the requested is routed to the HttpPost method. In looking at the request.form values, all expected data but paging information is present.
?HttpContext.Request.Form.AllKeys
{string[5]}
[0]: "IndustrySelectList"
[1]: "PagingInfo"
[2]: "SearchResults"
[3]: "searchTerm"
[4]: "industries"
Any help with this would be very much appreciated!
By clicking the button you are submitting the form which is why it is doing the httppost. The next page link is hitting the httpget correctly but you are not passing it any information to so that it knows what to get. The get needs other information, like what page you are wanting.
The page number links fire a GET request, so you'll need to make sure that your GET action can handle the full search as well, so will need to get the page number and industries array - using defaults for when those parameters aren't available.
e.g.
[HttpGet]
public ViewResult Search(string searchTerm = "", int page = 1,
string industries = "")
{
//.....
}
You'll need to modify the pager link like this to pass industries to the get action.
#Html.PagedListPager((IPagedList)Model.SearchResults, page => Url.Action("Search", "Home", new { page, industries = string.Join(",", Model.IndustrySelectList.Where( x => x.Selected).Select( x => x.Text)) }))
It's not clear to me from your code where the post action is getting string[] industries from, or what it is doing with it, but you will need some way of passing this same this to your get action, probably as a single string that is comma separated. The example I've provided assumed you are taken it from the select list on the viewmodel

Resources