17 Jul 2017

How to pass query string in MVC controller

How to pass query string in MVC controller




File => New Project
Templates => Visual C# => ASP.NET MVC Web Application

Right click on Models => Add => Class =>School.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QueryStringsinAsp.netMVC.Models
{
public class School
{
public int ID { get; set; }
public string Name { get; set; }
public int age { get; set; }

public List<School> StudentList = new List<School>();

public List<School> school()
{
StudentList.Add(new School() { ID = 1, Name = "Yapheth", age = 12 });
StudentList.Add(new School() { ID = 2, Name = "John", age = 12 });
StudentList.Add(new School() { ID = 3, Name = "Tom", age = 12 });
StudentList.Add(new School() { ID = 4, Name = "Levi", age = 12 });

return StudentList;
}
}

}
==================================================================================================
Controllers => Add Controller=> HomeController => Add
using QueryStringsinAsp.netMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QueryStringsinAsp.netMVC.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}

public ActionResult Search( string searchWord)
{
School s = new School();
var model = s.school().Where(x => x.Name.StartsWith(searchWord));
return View(model);
}

}
}
==================================================================================================
Right Click on Controller => Add View => Index => Add

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
@Html.TextBox("searchWord", null, new { @class = "form-control" });
<input type="submit" value="Search" class="btn btn-primary"/>
}
=================================================================================================
Right Click on search Controller => Add View =>Template List and model Class set to School => Add
@model IEnumerable<QueryStringsinAsp.netMVC.Models.School>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.age)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}

</table>
<a href="/Home/index">
<input type="button" class="btn btn-danger" value="Back" />
</a>



No comments:

Post a Comment