Enter multiple criteria in a search engine ASP. MVC3 - asp.net-mvc

I have the following code which looks into the "ProductCatalog" and returns items if found.
I need to edit the code in order for me to be able to enter multiple values or even special characters like >, <, and, or.
Is this possible?
<div class="search">
#*#using (Html.BeginForm("Search", "ProductCatalog", FormMethod.Get, new { name = "quickSearchform" }))*#
#using (Html.BeginForm("Search", "ProductCatalog", FormMethod.Get, new { name = "searchform", id = "searchform", onsubmit = "return validateSearch();" }))
{
#Html.TextBox("criteria", "Search", new
{
#class = "searchbox",
onfocus = "if (this.value==this.defaultValue) {this.value = ''}",
onblur = "if (this.value=='') {this.value = this.defaultValue}"
})
<a class="btn btnStyleC btn-search quickSearch" href="javascript:searchSumbitOnClick();">Search</a> #*<a class="btn btnStyleC btn-search" href="javascript:searchSumbitOnClick();">Search</a>*# } </div>

Related

Multiple parameters in mvc4

I am learning MVC and am stuck at this. I was trying to create a filter for name, category, type, Min Value, Max value but when redirected to another view it only shows three parameters but without other values.
Controller (DetailController)
public ActionResult FilteredResult(string searchedLocation, string Type, string PCName, string MinValue, string MaxValue)
{
var A = searchedLocation;
var B = Type;
var C = PCName;
var D = MinValue;
var E = MaxValue;
return View();
}
View
#using (Html.BeginForm("FilteredResult", "Detail", FormMethod.Get))
{
<form>
<h4 style="color: #ed145b;">Find the right property for you</h4>
<ul class="form-style-1">
<li>
#Html.TextBox("Location", ViewBag.Location as string , new { #class = "field-long" })
</li>
<li>
#Html.DropDownList("Type", (SelectList)ViewBag.TypeList, "Select" , new { #class = "field-select" })
</li>
<li>
#Html.DropDownList("Category", (SelectList)ViewBag.CategoryList, "Select" ,new { #class = "field-select" })
</li>
<li>
<label for="amount">Price range:</label>
<input type="text" id="amount" class="field-long" readonly style="border:0; color:#ee2265; font-weight:bold;">
</li>
<li class="clearfix"> #Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long", disabled = "true" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long", disabled = "true" })
</li>
<li>
<div id="slider-range"></div>
</li>
<li>
<input type="submit" value="Search" class="btn-primary" />
</li>
</ul>
</form>
}
After clicking on search it shows like this. Only the data from dropdown is shown and other parameter like Minvalue and max value is not shown in the url. Location is showing
Can anyone help me on how I can successfully get data in the required field in the controller?
It's because your MinValue and MaxValue textboxes have disabled="true" attribute. Disabled inputs won't be submitted
#Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long", disabled = "true" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long", disabled = "true" })
You should remove the disabled attribute
#Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long" })
If you want to make those textboxes non editable, use readonly attribute instead
#Html.TextBox("MinValue", ViewBag.MinValue as string, new { #class = "Minprice field-long", #readonly = "readonly" })
#Html.TextBox("MaxValue", ViewBag.MaxValue as string, new { #class = "Maxprice field-long", #readonly = "readonly" })
because you are using disabled attribute true that means it fetches data from database but will not show on View so either make disabled = "false" or remove this attribute.

#Html.BeginForm not working under the #If statement in Razor Code

Below is my razor code:
<div class="col-md-7 col-md-offset-5">
#if (Model.InvoiceStatus == "NEW")
{
Html.BeginForm("Delete", "Invoices", new { InvoiceID = Model.InvoiceID, #returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString()) }, FormMethod.Post);
#Html.AntiForgeryToken()
<input type="submit" value="Delete Invoice" class="btn btn-danger newbtn" style="float:right;margin-left:10px;" onclick="return confirm('Are you sure to delete this Invoice details?');" />
Html.EndForm();
#Html.ActionLink("Lock Invoice", "Lock", new { InvoiceID = Model.InvoiceID }, new { #class = "btn newbtn", #style = "float:right;margin-left:10px;" })
#Html.ActionLink("Edit Invoice", "Edit", new { InvoiceID = Model.InvoiceID }, new { #class = "btn newbtn", #style = "float:right;margin-left:10px;" })
}
#Html.ActionLink("Back", "Index", null, new { #class = "btn btn-default newbtn", #style = "width:100px;float:right;" })
</div>
The code didnt recognize the html.beginform, it just renders as input tag,
<input value="Delete Invoice" class="btn btn-danger newbtn" style="float:right;margin-left:10px;" onclick="return confirm('Are you sure to delete this Invoice details?');" type="submit">
Why it is not rendering as form?
You have to use it like
#if (Model.InvoiceStatus == "NEW")
{
using(Html.BeginForm("Delete", "Invoices", new { InvoiceID = Model.InvoiceID,
#returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString()) },
FormMethod.Post))
{
<!-- Your form elements goes here -->
}
}
This will generate the form tag when razor executes your code.
EDIT : From the comments
You should not have nested forms! That is invalid html. But you can still keep more than one form in the page (not nested, but siblings) as needed.

Action in controller received empty model from Html.BeginForm - ASP.NET MVC

I have stucked for 3 days. There is nowhere I had been looking for this problem. When I submit the form, Controller action method doesnt get the model.
My base view Login.cshtml
#{
string durum = ViewBag.Style;
switch (durum)
{
case "Login":
Html.RenderAction("_Login", "Dashboard");
break;
case "LostPassword":
Html.RenderAction("_LostPassword", "Dashboard");
break;
case "RegisterForm":
Html.RenderAction("_RegisterForm", "Dashboard");
break;
default:
Html.RenderAction("_Login", "Dashboard");
break;
}
}
One of my partial view _LostPassword.cshtml
#model HaberSitesi._Entities.Kullanici
#using (Html.BeginForm("LostPassword", "Dashboard", FormMethod.Post, new { #class = "forget-form", #style = "display:block" }))
{
if (TempData["ForgotPassword"] != null)
{
<div class="alert alert-warning ">
<button class="close" data-close="alert"></button>
<span>#TempData["ForgotPassword"]</span>
</div>
}
<h3>Şifrenizi mi unuttunuz ?</h3>
<p> Şifrenizi almak için lütfen E-Posta adresinizi giriniz. </p>
<div class="form-group">
<div class="input-icon">
<i class="fa fa-envelope"></i>
#Html.TextBoxFor(x => x.EPosta, new { #class = "form-control placeholder-no-fix", #type = "email", #autocomplete = "off", #placeholder = "Eposta", Name = "email" })
#Html.ValidationMessageFor(x => x.EPosta)
</div>
</div>
<div class="form-actions">
#Html.ActionLink("Geri Dön", "Login", "Dashboard", new { }, new { #type = "button", #id = "back-btn", #class = "btn grey-salsa btn-outline" })
<button type="submit" class="btn green pull-right"> Gönder </button>
</div>
}
And the action in controller DashboardController.cs
public ActionResult LostPassword()
{
VeriTransfer();
return View("Login");
}
[HttpPost]
public ActionResult LostPassword(Kullanici kullanici)
{
string kullaniciEposta = kullanici.EPosta;
Kullanici user = _kullaniciBll.Get(kullaniciEposta);
if (user != null)
{
TempData["ForgotPassword"] = "Şifreniz e-posta adresinize gönderildi.";
}
else
{
TempData["ForgotPassword"] = "Kayıtlarımızda e-posta adresiniz bulunamadı";
}
VeriTransfer();
return View("Login");
}
When I click submit button, I cant get any data (Kullanici kullanici) in controller. Every property comes null or default data value from model.
Note: Maybe my codes could have some other mistakes which are irrelevant with my problem. I just wonder why I get empty model. Thanks at least you have read my problem.
Your property is called EPosta but you changed the name of it to Name="email".So when the POST action happens it sends a property called email to the controller action and your Kullanici object expects a property called EPosta
Both of these will fix your problem:
Change Name="email" to Name="EPosta" or
Remove Name="email" completely
But like Stephen said it's better to remove it completely,because if you rename your property to EPosta2 in future and forget to change the name to Name="EPosta2" your POST will no longer work

MVC Form Losing Values During Server Side Validation

I am migrating an existing site from WebForms to MVC 5.
I have a Contact Us page that has client-side validation for checking if the fields are completed, etc. However, I am using BotDetect CAPTCHA which has server-side validation to check if the CAPTCHA was completed correctly.
If I enter the correct CAPTCHA, all works as expected -- an email is sent and all the form fields are represented in the email.
If I enter the wrong CAPTCHA, I should be returned to the form, an error message will be displayed for the invalid CAPTCHA but all the other fields should be still filled in.
However, this isn't happening. The form field is lost. I am guessing this is because the Model is getting regenerated. What I haven't figured out is how to get my ActionResult to just abandon doing any actions and leave the form contents in place.
My view:
#using BotDetect.Web.UI.Mvc;
#model Framework.Models.FrameworkModel
#section Styles {
<link href="#BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" rel="stylesheet" type="text/css" />
}
<h1>#Html.Raw(Model.Page.Heading)</h1>
<div class="main-container">
#if (string.IsNullOrWhiteSpace(ViewBag.Status))
{
#Html.Raw(Model.Page.Body)
<br />
<fieldset id="ContactFields" class="contact-fields">
<ol>
<li>
<label id="FullNameLabel" labelfor="FullName">#Resources.Contact.FullNameLabel</label>
#Html.TextBoxFor(model => model.Contact.FullName, new { #id = "FullName", #Name = "FullName", #class = "standard-textbox", #autocompletetype = "DisplayName", #data_validation_required = Resources.Contact.FullNameValidationErrorMessage})
</li>
<li>
<label id="EmailLabel" labelfor="Email">#Resources.Contact.EmailLabel</label>
#Html.TextBoxFor(model => model.Contact.Email, new { #id = "Email", #Name = "Email", #class = "standard-textbox", #autocompletetype = "Email", #data_validation_required = Resources.Contact.EmailValidationErrorMessage, #data_validation_format = Resources.Contact.EmailValidationErrorMessageFormat })
</li>
<li>
<label id="SubjectLabel" labelfor="Subject">#Resources.Contact.SubjectLabel</label>
#Html.TextBoxFor(model => model.Contact.Subject, new { #id = "Subject", #Name = "Subject", #class = "standard-textbox", #data_validation_required = Resources.Contact.SubjectValidationErrorMessage })
</li>
<li>
<label id="MessageLabel" labelfor="Message">#Resources.Contact.MessageLabel</label>
#Html.TextAreaFor(model => model.Contact.Message, new { #id = "Message", #Name = "Message", #class = "multiline-textbox", #rows = 5, #data_validation_required = Resources.Contact.MessageValidationErrorMessage })
</li>
<li>
<div class="captcha-control">
<br />
#{ MvcCaptcha captcha = Model.CaptchaHelper.GenerateCaptcha(); }
#Html.Captcha(captcha)
<br />
#Html.TextBox("CaptchaCode", "", new { #id = "CaptchaCode", #Name = "CaptchaCode", #class = "captcha-code short-textbox", #data_validation_required = Resources.Captcha.CaptchaValidationErrorMessage })
#Html.ValidationMessage("CaptchaCode")
</div>
<br />
<button id="SendButton" type="submit" class="send-button">#Resources.Contact.SendButton</button>
</ol>
</fieldset>
}
else
{
<span class="alert">#Html.Raw(ViewBag.Status)</span>
}
</div>
#section Scripts {
#Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\" defer=\"defer\"></script>", "~/bundles/scripts/contact")
}
Part of my controller (removed calls to irrelevant actions):
using Framework.App_Code.ViewRendering;
using Framework.Models;
using System.Web.Mvc;
using BotDetect.Web.UI.Mvc;
namespace Framework.Controllers
{
public class PagesController : AsyncController
{
[HttpGet]
[ActionName("Contact")]
public ActionResult Contact()
{
Contact viewRendering = new Contact();
return View(viewRendering.GenerateModel());
}
[HttpPost]
[ActionName("Contact")]
[AllowAnonymous]
[CaptchaValidation("CaptchaCode", "Captcha")]
public ActionResult ContactPost(ContactModel contactModel, bool captchaValid)
{
Contact viewRendering = new Contact();
if (ModelState.IsValid)
{
contactModel.IPAddress = Request.ServerVariables["REMOTE_ADDR"].Trim();
ViewBag.Status = viewRendering.SendMail(contactModel);
}
MvcCaptcha.ResetCaptcha("Captcha");
return View(viewRendering.GenerateModel());
}
}
}
When you return back to the view in the invalid case, pass the model back to have it re-displayed (i.e. when !ModelState.IsValid do this...)
return View(contactModel); // this is the one that was submitted

MVC 4 dropdownlist in edit form doesnt give the correct value after edit command from grid

This is very weird and i know that this worked in the past. I must have broken it with something else but I really don't know what.
I'm a .NET programmer with very little MVC knowledge and it seems that I'm missing some key things here , that mvc does in the background.
Let met explain it as best as I can.
I have a view, which contains this :
<tbody>
#foreach (var experienceViewModel in this.ViewData.Model)
{
var id = "GetExperienceDetail" + experienceViewModel.Id;
<tr>
<td>#experienceViewModel.Assessment</td>
<td>#experienceViewModel.CompanyName</td>
<td>#experienceViewModel.Description</td>
<td>#experienceViewModel.StartDate</td>
<td>#experienceViewModel.EndDate</td>
<td width="20"><i class="glyphicon glyphicon-pencil"></i></td>
<td width="20"><a id="#Html.Raw(id + "delete")" class="confirm-delete" data-keyname="experienceId" data-textfield="#string.Concat(experienceViewModel.Assessment, " | ", experienceViewModel.Description)" data-link="#Html.Raw(id + "delete")" data-key="#experienceViewModel.Id" data-controller="Experience" data-action="ExperienceDelete" href="#" title="Verwijder"><i class="glyphicon glyphicon-remove"></i></a></td>
</tr>
}
Its not the last tr but the one before that. The one with openDetail. This function will be called from the js web.js which I'm gonna paste below:
function openDetail(link) {
var $link = $('#' + link);
debugger;
var controller = $link.attr('data-controller');
var action = $link.attr('data-action');
var id = $link.attr('data-key');
var form = $link.attr('data-form');
var modelName = $link.attr('data-model');
//default person
if (modelName == null)
modelName = "person";
modelName = modelName.toLowerCase();
var valueModel = $link.attr('data-' + modelName);
var json = "{\"id\" : " + id + ", \"" + modelName + "\"" + " : " + valueModel + "}";
var url = '/' + controller + '/' + action;
$.ajax({
url: '/' + controller + '/' + action,
type: 'POST', // not sending json over url
data: json,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#partialoveview').html(data);
if (typeof form !== 'undefined' && form !== false) {
$.validator.unobtrusive.parse($('#' + form));
$("span.field-validation-valid").hide();
$('.label-error').hide();
}
loadForm();
},
error: function (data) {
}
});
This function does the job, the only thing that is going wrong is that dropdownlist, and specifically THAT one cause there is another one, below it , and this has the correct behavior of selecting the value that it has ...
This will go to the Person controller with the action ExperienceDetail(int id, int person)
[HttpPost, OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
public PartialViewResult ExperienceDetail(int id, int person)
{
var experienceViewModel = new ExperienceViewModel { AssessmentList = this.AssessmentList(), CompanyList = this.CompanyList(), PersonId = person };
if (id > 0)
{
Data.Model.Experience experience = this._experienceRepository.GetExperienceDetail(id);
experienceViewModel = new ExperienceViewModel(experience) { AssessmentList = this.AssessmentList(), CompanyList = this.CompanyList()};
}
return this.PartialView("_ExperienceDetailPartial", experienceViewModel);
}
this.CompanyList gets a select list from the basecontroller
When this view is returned , i cant see that this select list has a selectedvalue. But then again, the ddl which is working has also a null at the selectedvalue so this isn't responsable for setting the correct value after edit I guess?
Then the detail screen , which is put into a div from the js:
I only put in the beginning with first the company drop down ( NOT WORKING ) and then the assessment ddl ( WORKING )
#model Emenka.HumanResources.Application.Models.ExperienceViewModel
#using (Html.BeginForm("UpdateExperienceDetail", "Person", FormMethod.Post, new { #id = "ExperienceDetail", #role = "form", data_action = "ExperienceOverview", data_controller = "Person" }))
{
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.PersonId)
<fieldset>
<legend>Ervaring</legend>
<div class="row">
<div class="col-md-5">
<div class="form-group">
#Html.LabelFor(m => m.CompanyId, new { #class = "control-label" })
<div class="input-group col-xs-9">
#Html.DropDownListFor(m => m.CompanyId, ViewData.Model.CompanyList, string.Empty, new { #class = "no-focus form-control" })
#* #Html.ValidationMessageFor(m => m.CompanyId, " ")*#
...
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.AssessmentId, new { #class = "control-label" })
#Html.DropDownListFor(m => m.AssessmentId, ViewData.Model.AssessmentList, string.Empty, new { #class = "no-focus control-sm-7 form-control" })
#* #Html.ValidationMessageFor(m => m.AssessmentId, " ")*#
</div>
<div class="form-group">
#Html.LabelFor(x => x.StartDate, new { #class = "control-label" })
<div class="input-group col-xs-7">
#Html.TextBoxFor(x => x.StartDate, new { #class = "form-control date-picker", #readonly = "readonly" })
<label for="StartDate" class="input-group-addon glyphicon glyphicon-calendar add-on" />
</div>
</div>
I've searched and searched and i just have no clue what to search for . Can you guys give me tips plz ?
PS : dont mind the spaces at the data attrib, i was trying to get rid of the error when submitting this form at stackoverflow ( code 4 spaces ) .
i know the third parameter from the drop down is to select the default value, but this is string.Empty with the dropdownlist of assessment and this gets the correct value when clicking edit, and so not an empty string like the company dropdown... so logically this cannot be the problem
i found the problem !
Setting the viewdata property of the corresponding companyId which was linked to the dropdown, solved all my problems. I dont know why this worked at the other pages, maybe i just missed it .

Resources