I am using Razorview and Entity Framework and I am trying to achieve the following: I have a dropdown(id=ColumnName) that has a list of column names and a textbox(id=SearchValue) for value to be searched from a table. On click of a button, I am trying to retrieve from the database, the record where the column name is 'ColumnName' selected and value='SearchValue'. I am getting a 404 Resource Not found error on click of the button. I am not sure where I am going wrong. My code is as follows:
HTML:
<select id='mySelector' name="ColumnName">
<option value="">Please Select</option>
<option value='Country'>Country</option>
<option value='Title'>Title</option>
<option value='State'>State</option>
</select>
<input type="text" id="cs" name="SearchValue">
<input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "CountryController")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
<table id='myTable'>
// values
</table>
CountryController:
public ActionResult FilterByColumn(String ColumnName, String SearchValue)
{
if (!String.IsNullOrEmpty(SearchValue))
{
List<Country> result = new List<Country>();
result = db.Countries.ToList();
result = db.Countries.Where(ColumnName + ".Contains" + "(\"" + SearchValue.ToLower() + "\")").ToList();
return View(result);
}
return RedirectToAction("Index");
}
Note: I have other methods like create,edit in this controller.
Also the URL rendered which throws the 404 error is :
/CountryController/FilterByColumn?SearchValue=sample&ColumnName=Title
Your code as flollows
<input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "CountryController")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
Never give CountryController, just Give Country and try. Edit your code as follows and try
<input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "Country")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
and give the parameters in same order in both razor and controller
your button code as follows
input type="button" value="Search" onclick="location.href='#Url.Action("FilterByColumn", "CountryController")?SearchValue=' + document.getElementById('cs').value + '&ColumnName=' +document.getElementById('mySelector').value" />
but in the controller you have written as follows
public ActionResult FilterByColumn(String ColumnName, String SearchValue)
but the order of parameters are different. So change your controller as follows.
public ActionResult FilterByColumn(String SearchValue,String ColumnName)
Hope this will work out.
Related
This is the code in View Section:
<select name="country">
<option value="0">Select</option>
#foreach (var country in countries)
{
<option value="#country.CountryId"> #country.CountryName</option>
}
</select>
Code to get value from Controller:
public ActionResult IndexPost()
{
ViewBag.Countries = CountryRepository.GetCountries();
if (Request["btnSubmitCountry"] != null)
{
string country = Request["country"];
ViewBag.Msg = "You have selected " + country;
}
return View();
I wanted to Request to get value the name of the Country too, but right now it only gets the id. Can you please help me to get the id and name both using this only this method.
Because select returns the value of the value,But you can use the hidden tag to store the text value.
E.g:
<form onsubmit="var sel=document.getElementById('country');document.getElementById('country_text').value=sel.options[sel.selectedIndex].text;">
<select name="country" id="country">
<option value="0">Select</option>
#foreach (var country in countries)
{
<option value="#country.CountryId"> #country.CountryName</option>
}
</select>
<input type="hidden" name="country_text" id="country_text" />
</form>
get text:
string countryText = Request["country_text"];
I have a list In my view. For each row, I view button and I am passing Id value as hidden. But when I click any button it is passing wrong hidden value to the controller. Always it passes the first-row hidden value to the controller.
View:
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</div>
</div>
}
Controller:
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string viewId)
{
return RedirectToAction("ViewDetails");
}
To get all values you need to change the input value type in your controller to array of strings.
I hope that this solution can help you
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string[] viewId)
{
return RedirectToAction("ViewDetails");
}
if you want to get the exact value you need to duplicate the form within your foreach
in this case you should write somthing like this :
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<form ... > // complete your form attributes
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</form>
</div>
</div>
}
Note : You should delete the global form
You should have one form for each row. then you submit that row.
Otherwise as you state it passes first value.
You are setting each value to the same element ID (which is invalid anyway) and name. When you submit your form (which would be more helpful to fully answer your question) it is finding the first element that matches that criteria and submitting it.
There are multiple ways to resolve this such as the already mentioned form per entry but the other preference would be to modify you button to a div and add a click handler to pass the specific value to a js function which would then submit to the controller. Its a preference choice regarding how tightly coupled you want your front end. But the main problem is your element naming convention.
In the example below when clicking the button the value selected in the dropdownlist should be passed to the controller, but its not. How can I pass the value?
View:
#model BillingModel
...
<select id="ddl" asp-for="SelectedCompanyID" asp-items="Model.Companies" class="form-control"></select>
<a asp-action="Create" asp-controller="Invoice" asp-route-id="#Model.SelectedCompanyID" class="btn btn-primary btn-sm"></span> Create Invoice</a>
....
Model:
public class BillingModel
{
public int SelectedCompanyID { get; set; }
public SelectList Companies { get; set; }
}
Your link is using razor code to specify the route id value which is server side code. It does not change on the client side just because a option is selected.
Either use a form that makes a GET and submits the option value
<form asp-controller="Invoice" asp-action="Create" method="get">
<select id="ddl" asp-for="SelectedCompanyID" asp-items="Model.Companies" class="form-control"></select>
<input type="submit" value="Create Invoice" /> // you can style this to look like your link if you want
</form>
Note that this will generate the url with a query string value for the id, not a route value (i.e. it will generate ../Invoice/Create?id=1, not ../Invoice/Create/1)
Alternatively, you could use javascript/jquery to make the redirect by building a url based on the selected option
<a id="create" href="#" class="btn btn-primary btn-sm">Create Invoice</a>
$('#create').click(function() {
var baseUrl = '#Url.Action("Create", "Invoice")';
location.href = baseUrl + '/' + $('#SelectedCompanyID').val();
}
In a Asp.net MVC view, i created a form, with a input field.
The user Sets a first name (or part of it), presses the submit button.
This is the form section:
<div>
<form action="SearchCustomer" methos="post">
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
</form>
</div>
This is the SearchCustomer in the Controller, that gets the data from the form:
CustomerDal dal = new CustomerDal();
string searchValue = Request.Form["txtFirstName"].ToString();
List<Customer> customers = (from x in dal.Customers
where x.FirstName.Contains(searchValue)
select x).ToList<Customer>();
CustomerModelView customerModelView = new CustomerModelView();
customerModelView.Customers = customers;
return View("ShowSearch", customerModelView);
When i run the program, and enter a first name ("Jhon" for example), the code returns to SearchCustomer function, but Request.Form is empty.
Why?
Thanks.
Your method is spelled wrongly should not read methos but method like below:
<form action="SearchCustomer" method="post">
....
</form>
You need to modify your code:
you need to provide a action name here, which should be defined in your controller(SearchController) with the same name as 'ActionName' you will put in the below code.
if SearchController is your action name then provide the controller in which the action is available.
<div>
<form action="SearchCustomer/<ActionName>" method="post">
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
</form>
</div>
With Html.BeginForm :
#using (Html.BeginForm("<ActionName>","<ControllerName>", FormMethod.Post))
{
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
}
Set [HttpPost] on your controller.
[HttpPost]
public ActionResult SearchFunction(string txtFirstName)
{
CustomerDal dal = new CustomerDal();
string searchValue = txtFirstName;
List<Customer> customers = (from x in dal.Customers
where x.FirstName.Contains(searchValue)
select x).ToList<Customer>();
CustomerModelView customerModelView = new CustomerModelView();
customerModelView.Customers = customers;
return View("ShowSearch", customerModelView);
}
If you View is the same name as your ActionResult method, try this:
#using(Html.BeginForm())
{
... enter code
}
By default, it'll already be a POST method type and it'll be directed to the ActionResult. One thing to make sure of: You will need the [HttpPost] attribute on your ActionResult method so the form knows where to go:
[HttpPost]
public ActionResult SearchCustomer (FormCollection form)
{
// Pull from the form collection
string searchCriteria = Convert.ToString(form["txtFirstName"]);
// Or pull directly from the HttpRequest
string searchCriteria = Convert.ToString(Request["txtFirstName"]);
.. continue code
}
I hope this helps!
I have a Ajax.BeginForm in my razor view. I want to have 3 check boxes.
Begineer
Intemidiate
advance
checkoxes can select for any combination. When I clicked submit button bellow method in my controller will triggered.
public PartialViewResult SearchCourseCriteria(){
var courses = from s in db.CourseCategories
select s;
return PartialView("_Courses", courses);
}
This is my view
#using (Ajax.BeginForm("SearchCourseCriteria", new AjaxOptions
{
UpdateTargetId = "CourseList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
}))
{
td>
#Html.CheckBoxFor()
</td>
<td>
<input type="submit" value="Search" class="btn " />
</td>
}
In my model there is field called CourseLevel. I want to know How to filter courses according to the selected checkboxes.
EX : If I select begineer and Intermidiate checkboex. I want to get all courseCategories from that levels. I dont know how to get that result. Help please.
In you view, generate 3 checkboxes for each value
<label>
<input type="checkbox" name="courselevel" value="Begineer" /> // Beginner?
<span>Begineer</span>
<label>
<label>
<input type="checkbox" name="courselevel" value="Intemidiate" /> // Intermediate?
<span>Intemidiate</span>
<label>
... // ditto for advance
Then add a parameter to the method
public PartialViewResult SearchCourseCriteria(string[] CourseLevel)
The value of CourseLevel will be an array of the selected checkboxes, for example [ "Begineer", "advance" ] if you checked the first and third checkboxes
You can then modify you query to
var courses = from s in db.CourseCategories
where CourseLevel.Contains(s.CourseLevel)
select s;
or
var courses= db.CourseCategories.Where(c => CourseLevel.Contains(c.CourseLevel));
Side note: I would recommend you use an enum to define the values for CourseLevel