Can not implicitly convert System.Windows.Forms.Form to 'String' - c#

Hey so I have a modal popup form where I have to upload files and post data to the database. In the controller I'm retrieving the values by FormCollection. When I try to get the input fields with form collection i get this error : Can not implicitly convert System.Windows.Forms.Form to 'String'. Here is my code:
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection formCollection, HttpPostedFileBase upload, AAC_procedure_document_types model,NgarkoDokument ngarkoDok)
{
try
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var file = new AAC_procedure_documents
{
Emer_Dokumenti = System.IO.Path.GetFileName(upload.FileName),
Lloji_File = model.Emri_llojit,
Content_Type = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
file.Permbajtje_Dokumenti = reader.ReadBytes(upload.ContentLength);
}
ngarkoDok.AAC_procedure_documents = new List<AAC_procedure_documents> { file };
}
AAC_procedure_documents_location lokacion = new AAC_procedure_documents_location();
lokacion.Rafti = formCollection["Rafti"];
lokacion.Zyra = formCollection["Zyra"].ToString();
lokacion.Nr_Kutise = Convert.ToInt32(formCollection["Nr_Kutise"]);
db.AAC_procedure_documents_location.Add(lokacion);
db.SaveChanges();
return RedirectToAction("Dokumenti");
}
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(formCollection);
}
Html form
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ngarkoni dokumenta</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("Create", "NgarkoDokument", FormMethod.Post, new { enctype = "mulptiple/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
<label for="exampleFormControlSelect1">Lloji i dokumentit</label><br />
<select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>
<input type="button" title="Ngarko dokument" name="ngarko" value="Ngarko" id="uploadPop" class="btn btn-info col-md-3" onclick="document.getElementById('file').click();" />
<input type="file" onchange="javascript: updateList()" multiple="multiple" style="display:none;" id="file" name="postedFiles" />
<div id="fileList"></div>
</div>
<br /><br />
<div class="form-group">
<label for="formGroupExampleInput">Fusha indeksimi</label> <br />
#*<input title="Indeksimi dokumentit" id="indeksimi" class="form-control col-md-3" type="text" name="indeksimi" placeholder="indeksimi" required />*#
#Html.TextBoxFor(a => a.Fusha_Indeksimit.Emri_Indeksimit, new { #class = "form-control", #placeholder = "indeksimi" })
<button title="Shto indeksim" id="modalPlus" type="submit" class="btn btn-info"><i class="glyphicon glyphicon-plus"></i></button>
</div>
<label for="formGroupExampleInput">Vendndodhja fizike e dokumentit</label><br>
<div id="zyraModal" class="form-group col-md-4">
#*<input title="Zyra fizike" id="zyra" class="form-control" type="text" name="zyra" placeholder="Zyra" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Zyra, new { #class = "form-control", #placeholder = "Zyra" })
</div>
<div class="form-group col-md-4">
#* <input title="Kutia fizike" id="kutia" class="form-control" type="number" name="kutia" placeholder="Nr i kutisë" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Nr_Kutise, new { #class = "form-control", #placeholder = "Nr i kutisë" })
</div>
<div class="form-group col-md-4">
#* <input title="Rafti fizik" id="rafti" class="form-control" type="text" name="rafti" placeholder="Rafti" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Rafti, new { #class = "form-control", #placeholder = "Rafti" })
</div>
<br /><br />
<div class="row" id="ruaj">
<button value="Create" title="Ruaj dokumentin" type="submit" class="btn btn-success">Ruaj</button>
</div>
}
</div>
</div>

The namespace to FormCollection must to be System.Web.Mvc instead of System.Windows.Forms. Take a look in your usings and remove System.Windows.Forms...
The class FormCollection exists in two tecnologies, WindowsForm and Web.

Related

why does my page always redirects to the actionmethod view which doesnt exist rather than return to the view from where the actionmethod was called

I have a modal form that has a submit button already. Now I want to do a server-side validation for one of the data on the form. this validation will is meant to return a response to the user on the modal form if the data exist or not.
I am using an HTML action link to call an action method with ajax.
<div class="modal-body">
#using (Html.BeginForm("CreateSchool", "School", FormMethod.Post, new { enctype = "multipart/form-data", #class = "modal-form", id = "createSchoolForm" }))
{
#Html.AntiForgeryToken()
<div class="row forms">
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="createSchool_Name">
School Name <span class="text-danger">*</span>
</label>
<input type="text" class="form-control col-xs-10" name="Name" id="createSchool_Name" />
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="image">
School Logo
</label>
<div class="col-md-10">
<input type="file" accept="image/*" name="image" id="createSchool_image" />
<img id="img-header-create" class="img-responsive" style="height: 100px;" />
</div>
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="createSchool_Email">
Contact Email <span class="text-danger">*</span>
</label>
<input type="text" name="ContactEmail" class="form-control col-xs-12" id="createSchool_Email" />
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-12" for="createSchool_Number">
Contact Number <span class="text-danger">*</span>
</label>
<input type="text" name="ContactNumber" class="form-control col-xs-12" id="createSchool_Number" />
</div>
<div class="form-group col-xs-12">
<label class="control-label col-xs-4" for="createSchool_Subdomain">
School Subdomain <span id="domainspan"></span>
</label>
#Html.ActionLink("Check if Sub-Domain is available", "CheckDomain", null, new { #class = "col-xs-3", id = "CheckDomain" })
<p id="subdomainresult" class="col-sm-3">me</p>
#*<input type="submit" id="CheckDomain" name="CheckDomain" value="Check Sub Domain" class=" text-uppercase" />*#
#*<input id="CheckDomain_submit"> Check SubDOmain</input>*#
<input type="text" name="Subdomain" class="form-control col-xs-12" id="createSchool_Subdomain" />
</div>
<div class="form-group col-xs-12" style="margin-bottom: 25px;">
<label class="control-label col-xs-12" for="createSchool_StudentsCanEnrollForModules">
Students Are Allowed To Enroll For Modules (Learn More)
</label>
<div class="col-xs-10">
<div class="forms__checkbox">
<input type="checkbox" name="StudentsCanEnrollForModules" class="checkbox" id="createSchool_StudentsCanEnrollForModules" checked />
</div>
</div>
</div>
<div class="form-group col-xs-12" style="margin-bottom: 25px;">
<label class="control-label col-xs-12" for="createSchool_PrivateSchool">
This is a Private School (Learn More)
</label>
<div class="col-xs-10">
<div class="forms__checkbox">
<input type="checkbox" name="PrivateSchool" class="checkbox" id="createSchool_PrivateSchool" />
</div>
</div>
</div>
<div class="form-group col-xs-12">
<label class="control-label">
Description
</label>
#*<textarea type="text" name="Description" class="form-control col-xs-12" id="createSchool_Description"></textarea>*#
<div id="createSchool_Description_div" style="height:300px;"></div>
</div>
<div class="form-group col-xs-12">
<input type="button" id="createSchool_submit" value="Create" class="btn btn-success text-uppercase" />
<button type="button" class="btn btn-default text-uppercase" data-dismiss="modal">Close</button>
<img class="preloader_image" style="height: 30px" src="~/images/loadingicon_large.gif" />
</div>
</div>
}
</div>
This is my jquery ajax code that calls the action method to validate the user input
$("#CheckDomain").click(function () {
debugger;
var sch = new Object();
sch.SubDomain = $('#createSchool_Subdomain').val();
if (sch != null) {
$.ajax({
url: "/School/CheckDomain",
//url: "#Url.Action("CheckDomain", "School")",
type: "POST",
data: JSON.stringify(sch),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
debugger;
if (response != null) {
switch (response) {
case true:
//$("#subdomainresult").html("Submdomain already exists ");
alert("Submdomain already exists " );
break;
case false:
alert("Submdomain is available ");
//$("#subdomainresult").html("Submdomain is available ");
break;
default:
}
} else {
alert("Please enter a subdomain to check availability");
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
});
this is my action method
[HttpPost]
public ActionResult CheckDomain(CreateSchoolViewModel sch)
{
string SubDomain= sch.Subdomain;
if (!string.IsNullOrWhiteSpace(SubDomain))
{
var IsSubdomianAvailable = Util.getSchoolFromSubdomain(databaseHandler, SubDomain);
if (IsSubdomianAvailable == null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
return Json(null, JsonRequestBehavior.AllowGet);
}
the page always tries to redirect to the action name( checkdomian) view rather than remain on the page
This line
#Html.ActionLink("Check if Sub-Domain is available", "CheckDomain", null, new { #class = "col-xs-3", id = "CheckDomain" })
can be replaced with a link with href set to javascript:void(0)
<a id='CheckDomain' href='javascript:void(0)' class='col-xs-3'>Check if Sub-Domain is available</a>
The link can be void, since there is a JQuery click event handler attached to it.

Modal Dialog No Redirect

I use C# MVC version 5. I have a form in a modal dialog, which uses a partial view. I want to submit the form and not redirect. I just want the dialog to close. Can this be done?
Here is my code:
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-success">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title">#title</h5>
</div>
#using (Html.BeginForm("Edit", "Region", FormMethod.Post, new { onsubmit = "return validateForm();", #class = "form-horizontal" }))
{
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Submit form</button>
</div>
}
</div>
</div>
public ActionResult Edit(int id)
{
RegionViewModels regionViewModels = MakeRegionViewModels(id);
return PartialView("_InsertTaxRegion", regionViewModels);
}
With jQuery you can just serialize the form data and send it to the server in the background and you can close your modal, here is an example:
How to use jquery $.post() method to submit form values
If you are using <input type="submit" /> instead of <button type="button">Submit</button> then you'll need to prevent your form from submitting like this:
Using JQuery - preventing form from submitting
You can do this with a Bootstrap modal without the jQuery code.
On the page where I want to display the modal. Your modal form (PartialView) will display on top of the view you're already on.
<button id="btn" type="button" class="btn btn-info btn-lg" data-toggle="modal" data- target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog" data-toggle="modal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
#Html.Partial("Modal");
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div>
</div>
Your modal displays in a PartialView...
#model NCR.Models.Employee
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.FIRST_NAME, htmlAttributes:
new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FIRST_NAME,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FIRST_NAME, "",
new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LAST_NAME, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LAST_NAME, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LAST_NAME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-default" />
</div>
</div>
}

Request is not receiving file - Asp.Net Mvc

I'm trying upload a file from my page, but the request is not receiving posted file.
My form is into a normal Bootstrap modal, and this is the view.
#model InventarioWeb.Mvc.ViewModels.InventarioViewModel
<!-- Modal -->
<div id="ImportadorModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Importar Arquivo</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("ImportarItensInventario", "Inventario", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<div class="col-md-10">
#*<h4>Input Groups</h4>*#
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Procurar…
<input type="file"
id="fileToUpload"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<span class="help-block">
Selecione um arquivo
</span>
</div>
<div class="col-md-10">
<input type="submit" id="SubmitArquivoInventario" name="Submit" value="Salvar Arquivo" class="btn btn-primary" disabled="disabled"/>
</div>
</div>
#*#Html.HiddenFor(x => x.InventarioId)*#
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And this is the controller's method
[HttpPost]
public ActionResult ImportarItensInventario(Guid inventarioId)
{
if (Request.Files["UploadInventarioItems"] == null || Request.Files["UploadInventarioItems"].ContentLength == 0)
{
return RedirectToAction(nameof(Details), new { id = inventarioId });
}
string path = $"{Server.MapPath("~/Uploads")}/{Request.Files["UploadInventarioItems"].FileName}";
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
Request.Files["UploadInventarioItems"].SaveAs(path);
var model = new InventarioViewModel {InventarioId = inventarioId};
var result = _arquivoAppService.ImportarArquivo(InventarioViewModel.ToModel(model), Request.Files["UploadInventarioItems"].FileName);
return RedirectToAction(nameof(Details), new { id = inventarioId});
}
When I request, the id parameter is received, but my file isn't.
Besides, the Request.Files does not have any item.
What I'm doing wrong??
Add name attribute to your input type file, you can workaround to get the file without this attribute, but it's more convenient.
<input type="file" id="fileToUpload" name="upload" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
and use in server this method to get the file:
if (Request.Files["upload"] == null || Request.Files["upload"].HasFile())
{
//do something
}
or like this for multiple files:
foreach (string inputTagName in Request.Files)
{
if (!Request.Files[inputTagName ].HasFile()) continue;
//... continue processing
}

Model Error Not Showing after Http Post MVC 4

I am validating date input server side and adding ModelError if user input is invalid. Following is my code
public ActionResult EditOffer()
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var objOffer = context.tbl_offer.Where(x => x.LNG_OFFER_ID == offerID).FirstOrDefault();
ViewBag.OfferID = offerID;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
if (System.IO.File.Exists(Server.MapPath(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID))))
{
objOffer.TXT_OFFER_SMALL_PATH = string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], offerID);
}
return View("AddOffer", objOffer);
}
}
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return RedirectToAction("EditOffer");
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
return RedirectToAction("EditOffer");
}
View
<div class="panel-body container-fluid">
#using (Html.BeginForm("EditOffer", "Store", FormMethod.Post, new { #class = "form-horizontal", enctype = "multipart/form-data" , id="offerForm"}))
{
#Html.AntiForgeryToken();
#Html.ValidationSummary(true);
<div class="form-group">
<label class="col-sm-3 control-label">Offer Title</label>
<div class="col-sm-6">
#Html.TextBoxFor(model => model.TXT_OFFER_TITLE, new { #class = "form-control", placeholder = "Offer Title", autocomplete = "off", name = "title" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TITLE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Banner</label>
<div class="col-sm-9">
<div class="image-container" style=" border: 1px solid #ccc; display: table;position:relative">
<a href="#editimage" data-toggle="modal" class="btn btn-sm btn-icon btn-inverse btn-round btn-image-edit" data-toggle="tooltip" data-original-title="Edit">
<i class="icon wb-pencil" aria-hidden="true"></i>
</a>
<div class="img-preview preview-lg">
<img id="image_upload_preview" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="width:100%" alt="your image" />
</div>
</div>
<div class="input-group-file" style="margin-top:5px">
#Html.TextBoxFor(modal => modal.TXT_OFFER_SMALL_PATH, new { #class = "hide", #readonly = "true", width = "0", id = "filePath" })
#Html.ValidationMessageFor(modal => modal.TXT_OFFER_SMALL_PATH, "", new { #class = "text-danger" })
<span class="">
<span class="btn btn-success btn-small btn-file">
Upload Image <i class="icon wb-upload" aria-hidden="true"></i>
<input type="file" name="files" accept="image/*" multiple="" id="fileupload" onchange="showimagepreview(this)">
</span>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Offer Detail </label>
<div class="col-sm-6">
#Html.TextAreaFor(model => model.TXT_OFFER_TEXT, new { #class = "form-control", placeholder = "Offer Text", autocomplete = "off", name = "text" })
#Html.ValidationMessageFor(model => model.TXT_OFFER_TEXT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Valid For</label>
<div class="col-sm-4">
<div class="input-daterange" data-plugin="datepicker">
<div class="input-group">
<span class="input-group-addon">
<i class="icon wb-calendar" aria-hidden="true"></i>
</span>
#Html.TextBoxFor(model => model.DAT_START_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control from_date", placeholder = "Start Date", autocomplete = "off", name = "start" })
#Html.ValidationMessageFor(model => model.DAT_START_OFFER, "", new { #class = "text-danger" })
</div>
<div class="input-group">
<span class="input-group-addon">to</span>
#Html.TextBoxFor(model => model.DAT_END_OFFER, "{0:dd MMMM yyyy}", new { #class = "form-control to_date", placeholder = "End Date", autocomplete = "off", name = "end" })
#Html.ValidationMessageFor(model => model.DAT_END_OFFER, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Is Premium</label>
<div class="col-sm-4">
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 1, new { #id = "ispremiumYes", name = "ispremium", #checked = "checked" })
<label for="ispremiumYes">Yes</label>
</div>
<div class="radio-custom radio-default radio-inline">
#Html.RadioButtonFor(model => model.INT_IS_PRIME, 0, new { #id = "ispremiumNo", name = "ispremium", })
<label for="ispremiumNo">No</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-3">
<button type="submit" name="#ViewBag.ActionToPerform" class="btn btn-primary">Submit </button>
<button type="reset" class="btn btn-default btn-outline">Reset</button>
</div>
</div>
#Html.Hidden("cropWidth", new { id = "cropWidth" })
#Html.Hidden("cropHeight", new { id = "cropHeight" })
#Html.Hidden("cropPointX", new { id = "cropPointX" })
#Html.Hidden("cropPointY", new { id = "cropPointY" })
#Html.Hidden("ImgSrc", new { id = "ImgSrc" })
}
<div class="modal fade" id="editimage" aria-labelledby="modalLabel" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document" style="width:1024px;height:768px">
<div class="modal-content ">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalLabel">Crop the image</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-9">
<div class="cropper text-center">
<img id="image" src="#Url.Content(string.Format("~/assets/images/Stores/{0}/O_{1}_Small.jpg", Session["StoreID"], ViewBag.OfferID))" style="max-width:730px;" alt="Picture">
</div>
</div>
<div class="col-sm-3">
<div class="docs-preview clearfix">
<div class="img-preview preview-lg"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
But Modal Error is not showing on view. What could be the cause ?
When you set your model error then you use RedirectToAction, what mean that you load new page, check in your debug, after that your code go back to GET method and everything is reloaded.
You have to return your View with model.
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available");
if (Edit != null)
{
return View(modal); //if your model is object named modal
}
You didn't see any error because of RedirectToAction. You should use the "View" method. For example you can just write return EditOffer()
If you use return RedirectToAction("EditOffer"); the error will not been show it will be redirect to public ActionResult EditOffer(){} Action method, the [HttpGet] will be shown. To rectify this error, you should use View() method. like return View(); it return the error to the form data posted page.
[HttpPost]
public ActionResult EditOffer(tbl_offer modal, string Add, string Edit)
{
if (ModelState.IsValid)
{
using (joyryde_storeEntities context = new joyryde_storeEntities())
{
var offerID = Convert.ToInt64(Request.RequestContext.RouteData.Values["id"]);
if (!isOfferExist(modal.DAT_START_OFFER.Value.Date, modal.DAT_END_OFFER.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999), Convert.ToInt64(Session["StoreID"]), offerID, Add, Edit, context))
{
// My Code
return RedirectToAction("AllOffers", "Store");
}
else
{
ModelState.AddModelError("DAT_START_OFFER", "Date Not Available"); // Here i am adding Modal Error For Date
if (Edit != null)
{
return View(modal);
}
else
{
return RedirectToAction("AddOffer");
}
}
}
}
else
{
ViewBag.OfferID = Here give the office id;
ViewBag.Header = "Edit " + objOffer.TXT_OFFER_TITLE;
ViewBag.ActionToPerform = "Edit";
ModelState.AddModelError("","Your Error Message"); // Here i am adding Modal Error For Date
return View(modal);
}
}

show find textbox and 2 drop down list in the same line in a mvc form using bootstrap 3

I want to display a search box, submit button and 2 drop down boxes in the same line for ipads to large screens. If the screen is smaller than ipad size it will break in to 2 or 3 lines. I tried all samples given in here, but no luck.
I am using ASP.NET MVC 4.Here is my code:
Index.cshtml
<div class="row">
<div class="abc">
#using (Html.BeginForm("Contact", "Home", FormMethod.Get, new { id = "f1", #class = "form-inline" }))
{
<div class="form-group col-xs-6 col-lg-4">
<label class="sr-only" for="find-input">Find: </label>
<div class="input-group ">
<input type="text" name="filter" value="#ViewBag.filter" class="form-control" placeholder="Search by Product or Description" id="find-input" />
<span class="input-group-btn ">
<button class="btn btn-default" type="submit" onclick="this.form.submit();">Go</button>
</span>
</div>
</div>
<div class="col-xs-6 col-lg-4">
<div class="form-group ">
<div class="input-group ">
<label class="control-label " for="sort-drop-down">Sort </label>
#Html.DropDownList("sortColumn", ViewBag.SortColumns as SelectList, "", new { onchange = "this.form.submit();", #class = "form-control", id = "sort-drop-down" })
</div>
</div>
</div>
<div class="col-xs-6 col-lg-4">
<div class="form-group ">
<label class="control-label " for="page-size-drop-down">Show </label>
<div class="input-group ">
#Html.DropDownList("pageSize", ViewBag.pageSizes as SelectList, "", new { onchange = "this.form.submit();", #class = "form-control", id = "page-size-drop-down" })
</div>
</div>
</div>
<input type="hidden" name="viewMode" id="hd1" value="#ViewBag.DisplayMode" />
}
</div>
</div>
HomeController.cs
public ActionResult Index(int pageSize = 8, string sortColumn = "Id", string viewMode = "grid")
{
ViewBag.Message = "Your contact page.";
Dictionary<string, string> sortByColumnsList = new Dictionary<string, string>() { { "Id", "Id" }, { "ProductName", "Product Name" }, { "Description", "Description" } };
ViewBag.SortColumns = new SelectList(sortByColumnsList, "Key", "Value", sortColumn); // NOTE: To set a default value(4) we can use: new SelectList(sortByColumnsList, "Key", "Value", "Id=4")
//Page Sizes
List<string> pageSizeList;
if (viewMode.ToLower() == "table")
{
pageSizeList = new List<string>() { "10", "25", "50", "100" };
if (pageSizeList.IndexOf(pageSize.ToString()) < 0)
{
pageSize = 10;
}
}
else
{
pageSizeList = new List<string>() { "8", "12", "16", "20" };
if (pageSizeList.IndexOf(pageSize.ToString()) < 0)
{
pageSize = 8;
}
}
ViewBag.pageSizes = new SelectList(pageSizeList, pageSize);
return View();
}
CSS
.abc {
margin-top: 10px;
}
Please can someone help?
You have just handled case for a large device(col-lg) or an extra small device(xs). So when customising customise it for md as well i.e. Medium Sized devices.
In your case just don't handle it and let outer inline-form class handle it for you.
Also, try enclosing your row within a div with class container. As I'm not much familiar with .NET, but let's say we are observing our final html page obtained.
See sample output fiddle here.
https://jsfiddle.net/3vnxncke/
Also, see screenshots below for same scenarios with the code by screen adjustment.
You may try adjusting html screen size to see other device scenarios.
Hope it helps.
If someone having same issue when using MVC templates, I would like to show what I have done to fix this issue. The correct way to use bootstrap html is described on #Vinay Prajapati's answer. Although it works for pure html page it doesn't work when we use MVC scaffolding. So I have made some css adjustment as follows.
.input-group
{
display:inline-table;
}
.control-label{
vertical-align:middle;
}
.form-group .control-label
{
margin-top:-15px;
}
.input-group-btn{
width:auto;
}
Adjusted html
<div class="container body-content">
<form class="form-inline" id="f1" method="get">
<div class="row">
<div class="form-group">
<label class="sr-only" for="find-input">Find: </label>
<div class="input-group ">
<input type="text" name="filter" value="ViewBag.filter" class="form-control" id="find-input" />
<span class="input-group-btn ">
<button class="btn btn-default" type="submit" onclick="this.form.submit();">Go</button>
</span>
</div>
</div>
<div class="form-group">
<label class="control-label " for="sort-drop-down">Sort </label>
<div class="input-group ">
<select class="form-control" id="sort-drop-down" name="sortColumn" onchange="this.form.submit();">
<option selected="selected" value="Id">Id</option>
<option value="ProductName">Product Name</option>
<option value="Description">Description</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label " for="sort-drop-down">Show: </label>
<div class="input-group ">
<select class="form-control" id="page-size-drop-down" name="pageSize" onchange="this.form.submit();">
<option>8</option>
<option>12</option>
<option>16</option>
<option>20</option>
</select>
</div>
</div>
</div>
</form>
</div>

Categories

Resources