I'm using GridMvc and I'm filtering data. I'd like to hide filter query in the url like http://www.mypage.com/Overview?Name=yyy
My form is defined as:
<form class="form-inline" method="POST" action="#Url.Action("Filter", Request.QueryString)">
<div class="form-group>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name, new { placeholder = "Filter", #class = "form-control" })
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
And the action
[HttpPost]
public ActionResult Filter(FilterModel model)
But I always see the query. It's possible to hide query string?
You cound hide your query if you put all you data in hidden fields instead of Request.QueryString.
I mean if your Request.QueryString looks like param1=test1¶m2=test2 you should render you view like this:
<form class="form-inline" method="POST" action="#Url.Action("Filter")">
<input type="hidden" name="param1" value="test1" />
<input type="hidden" name="param2" value="test2" />
<div class="form-group>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name, new { placeholder = "Filter", #class = "form-control" })
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
MVC binding will bind all hidden values on POST according to name property of this hidden inputs.
You should just fill inputs value (replace test1 and test2 with your values from Request.QueryString)
Related
I am trying to search a student and display the student record based on the value entered on textbox. I am not sure how to pass the value without using Jquery. Is there a way.
Controller:
[Authorize]
public ActionResult GetStudentsByName(string name)
{
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
View
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m=> m.SearchEntity.StudentName,"Search Student")
#Html.TextBoxFor(m => m.SearchEntity.StudentName, new { #class = "form-control" })
</div>
</div>
<div class="panel-footer">
<button type="button" onclick="location.href='#Url.Action("GetStudentsByName", "Student")'" class="btn btn-primary">Search <i class="glyphicon glyphicon-search"></i></button>
<button id="Reset"
class="btn btn-primary btn-sm">
<i class="glyphicon glyphicon-share-alt"></i> Reset
</button>
</div>
I need to pass the param , In the #Url.Action("GetStudentsByName", "Student", new {#name= 'value from the textbox')
Also it is a Get Method and not httpPost.
You can keep the input form element inside a form control and submit the form via GET method.
Make sure the input element name matches with your action method parameter name
#using (Html.BeginForm("GetStudentsByName","Student",FormMethod.Get))
{
<input type="text" name="name"/>
<button type="submit" class="btn btn-primary">Search </button>
}
If you dont wanna make the button a submit button then by giving your text box a specific class you can do it .
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m=> m.SearchEntity.StudentName,"Search Student")
#Html.TextBoxFor(m => m.SearchEntity.StudentName, new { #class = "form-control,txt-input" })
</div>
</div>
<div class="panel-footer">
<button type="button" onclick="location.href='#Url.Action("GetStudentsByName", "Student",new { data= "STUDENT_NAME" })'.replace("STUDENT_NAME", $('.txt-input').val())" class="btn btn-primary">Search <i class="glyphicon glyphicon-search"></i></button>
<button id="Reset"
class="btn btn-primary btn-sm">
<i class="glyphicon glyphicon-share-alt"></i> Reset
</button>
</div>
I tried something like this long back , i think it should work.
Try this
View
#using (Html.BeginForm("GetStudentsByName", "Home"))
{
<div class="form-group">
#Html.LabelFor(m => m.StudentName, "Search Student")
#Html.TextBoxFor(m => m.StudentName, new { #class = "form-control" })
</div>
<input type="submit" value="Search" class="btn btn-primary" />
}
</div>
Controller
public ActionResult GetStudentsByName()
{
string name = Request.Form["StudentName"]
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
using Request.Form["StudentName"] you can access the value from view to controller. Also, one more suggestion, use using statement it helps to manage unhandled memory. For example
public ActionResult GetStudentsByName()
{
string name = Request.Form["StudentName"]
using(SchoolDbEntities db = new SchoolDbEntities())
{
var student = db.Students.Where(s => s.StudentName.Contains(name));
return View(student);
}
}
Model property which I intend to use inside two forms
public class TestModel
{
[Display(Name = "Terms Accepted")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You need to accept terms and conditions to proceed!")]
public bool TermsAccepted { get; set; }
}
view Page
<form id="form1">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted, new { #id = "chk1" })
</div>
<div class="col-md-3">
<input type="submit" id="button1" onclick="return isFormValid('form1');" value="Submit Form 1"/>
</div>
</div>
</form>
<form id="form2">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted, new { #id = "chk2" }) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted)
</div>
<div class="col-md-3">
<input type="submit" id="button2" onclick="return isFormValid('form2');" value="Submit Form 2"/>
</div>
</div>
</form>
When this UI is rendered on the page, checkbox inside the 1st form do contains attributes for RangeDataAnnotation while checkbox inside 2nd form doesn't have any attributes for data annotation. So this results into 2nd form doesn't throw any validation on submission.
Html of checkboxes which get rendered on UI
Inside form 1:
<input name="TermsAccepted" class="input-validation-error" id="chk1" aria-describedby="TermsAccepted-error" type="checkbox" value="true" data-val="true" data-val-range-min="True" data-val-range-max="True" data-val-range="You need to accept terms and conditions to proceed!">
Inside form 2:
<input name="TermsAccepted" id="chk2" type="checkbox" value="true">
Any suggestions to make this work in both forms?
I have a form that submits a SearchByUserViewModel (containing only string ID) to asp-controller="Home" asp-action="SubmitUserSearch". The form is a single textbox and a submit button. SubmitUserSearch retrieves the ID from the model and returns RedirectToAction("EventListByArtist", m.ID).
EventListByArtist, in the Home controller, is as follows:
public IActionResult EventListByArtist(string ID)
{
var events = context.Events.ToList();
ViewBag.genres = context.Genres.ToList();
ViewBag.artists = context.Artists.ToList();
ViewBag.ID = ID;
return View("EventList", events);
}
SubmitUserSearch redirects to EventListByArtist:
public IActionResult SubmitUserSearch(SearchByUserViewModel m)
{
return RedirectToAction("EventListByArtist", m.ID);
}
The SearchByUserViewModel contains only the ID field.
However, something in the middle breaks, and instead of being directed to (for example input "Bob") Home/EventListByArtist/Bob, I am directed to Bob/EventListByArtist, which does not exist. What is causing this redirect? The form has been pasted below.
<form asp-controller="Home" asp-action="SubmitUserSearch" asp-route-returnurl="#ViewData["ReturnUrl"]" class="form-horizontal">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="ID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ID" class="form-control" id="artistInput" />
<span asp-validation-for="ID" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Search" />
</div>
</div>
</form>
The project routes declaration (in Startup.cs) is as follows:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
In your SubmitUserSearch() POST method the value of m.ID is a string ("Bob") so you RedirectToAction() translates to
return RedirectToAction("EventListByArtist", "Bob");
which is using this overload where the 2nd parameter is the name of the controller, hence it generates /Bob/EventListByArtist.
You need to use this overload where the 2nd parameter is object
return RedirectToAction("EventListByArtist", new { id = m.ID });
Am I missing something? I copied this code snippet over:
Automatically render the reCAPTCHA widget
I entered my registered data-sitekey. The reCAPTCHA displays and works when I check the box, but if I don't check the box and submit my form, the reCAPTCHA doesn't stop the user submission and my controller processes the request.
#model Medicaid.WebUI.ViewModels.RequestModel
<script src='https://www.google.com/recaptcha/api.js' async defer></script>
<table class="table">
<tr>
<td>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "request-form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
<fieldset>
<legend>Request</legend>
<div class="form-group">
<label for="inputFirstName" class="col-lg-2 control-label">First Name</label>
<div class="col-lg-10">
<input type="text" value="#Model.FirstName" class="form-control" maxlength="50" name="FirstName" id="FirstName" placeholder="First Name" required>
</div>
</div>
<div class="form-group">
<label for="inputLastName" class="col-lg-2 control-label">Last Name</label>
<div class="col-lg-10">
<input type="text" value="#Model.LastName" class="form-control" maxlength="50" name="LastName" id="LastName" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" value="#Model.Email" class="form-control" maxlength="100" name="Email" id="Email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2"><br /><br />
<div class="g-recaptcha" data-sitekey="IenterMykeyHere"></div><br /><br />
<button type="submit" class="btn btn-primary">Submit Request</button>
</div>
</div>
</fieldset>
}
</td>
</tr>
</table>
<br /><br />
#Html.ValidationSummary()
I was having this issue and re-read the documentation, and worked it out as the following:
function onBegin() {
$("input[type='hidden']").val(grecaptcha.getResponse());
}
You have to add a javascript function to the "onBegin" parameter of the AjaxOptions object from the MVC html helper - that will copy the value of the widget's response to a hidden variable you need to declare inside your form, so the submit button sends it to the controller. Don't forget to add a variable with the same name to the "RequestModel" view model so that the mvc model-binding passes it and you then will be able, in the server, to know if the user has clicked the button or not.
#using (Ajax.BeginForm("NewRecaptchaVerify", "ReCaptcha", new AjaxOptions
{
HttpMethod = "Post",
OnSuccess = "onSuccess",
OnFailure = "onFailure",
OnBegin = "onBegin",
OnComplete = "onComplete"
}))
{
#Html.HiddenFor(m => m.Response)
<div class="g-recaptcha" data-sitekey="your-site-key"></div>
<input type="submit" id="btnSubmit" value="Submit" />
}
(for the record, I am now facing the problem of knowing, in the server, in cases where the widget prompted the user to enter a text input, after clicking the button - whether he/she entered the text or not. Seems to me that in the end I will have no way out other than performing a GET request, in the server, to the widget's api, as they put it in the documentation: https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address
I need to create a simple radio button list selection to choose from the following values:
Agree
Disagree
Not sure
How would we add it in the following razor view? Is it better to create an enum of these values in the QuestionModel and use foreach to bind with html helper.
Any example or ideas?
#model Survey.Models.Question
#using (Html.BeginForm("Index", "Home", new { QuestionId = Model.QuestionId }))
{
<h2>Survey</h2>
<fieldset>
<legend>Please Choose</legend>
<p>
Question ID:
#Model.QuestionId
</p>
<p>
Description:
#Model.Description
</p>
<input type="submit" value="Next" id="submitButton" />
</fieldset>
}
Using the ASP.NET Html Helpers, there are three various methods you can use for each of the different helpers supplied for radio buttons.
Method 1
A simple way to make a radio button list:
<div>
<label>
#Html.RadioButton("Answer", "Agree")
Agree
</label>
</div>
<div>
<label>
#Html.RadioButton("Answer", "Disagree")
Disagree
</label>
</div>
<div>
<label>
#Html.RadioButton("Answer", "Not Sure")
Not Sure
</label>
</div>
Method 2
The above code will post the checked value with a name of "Answer" to the server when you click Submit. If you would like to make this strongly typed, as you did with Model.QuestionId and Model.Description, you could add a Answer property to your model and do the following:
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Agree")
Agree
</label>
</div>
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Disagree")
Disagree
</label>
</div>
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Not Sure")
Not Sure
</label>
</div>
Method 3
Finally, if you would like to get fancy, you can use an enum. Place the following in your controller:
public enum AnswerType {
Agree,
Disagree,
NotSure
}
Next, add the property to your model:
public AnswerType AnswerType { get; set; }
And then add the following to your view:
#Html.RadioButtonForEnum(m => m.AnswerType)
Hope this helps!
this will work
Radio button for model
#using (Html.BeginForm())
{
foreach (var department in Model.Departments)
{
#Html.RadioButtonFor(m => m.SelectedDepartment, department.Id) #department.Name
}
<input type="submit" value="Submit" />
}
In your viewmodel you could have a public int SelectedRating. You could make it a string and change the values from 114... to string values as well.
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 114)
<span>Not Sure</span>
</label>
</div>
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 115)
<span>Agree</span>
</label>
</div>
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 116)
<span>Don't Agree</span>
</label>
</div>