How to format dynamic controls in MVC 5 - razor

In the following code from my MVC 5 View, I am dynamically building label and textbox controls but I need to format them in a table so I am not sure how I can do this.
#using InFlowConvertWeb.WebUI.Models
#model InFlowConvertWeb.WebUI.Models.SearchControlListViewModel
#{
ViewBag.Title = "List";
}
#using (Html.BeginForm())
{
int searchControlIndex = 0;
foreach (SearchControl searchControl in Model.SearchControls)
{
switch (searchControl.ControlType)
{
case SearchControl.ControlTypes.TextBox:
{
<div class="form-group" style="margin-left: 15px">
#Html.Label(searchControl.FieldName,
new { #class = "col-md-12 control-label" })
#Html.TextBoxFor(
x => x.SearchControls[searchControlIndex].SearchValue)
#Html.HiddenFor(x => x.SearchControls[searchControlIndex].DataTable)
#Html.HiddenFor(x => x.SearchControls[searchControlIndex].FieldName)
</div>
break;
}
}
searchControlIndex += 1;
}
<div class="col-md-2">
<h2>
<input type="submit" value="Submit Selections" />
</h2>
</div>
Any suggestions would be greatly appreciated,
Bob

Try this Example:
#using InFlowConvertWeb.WebUI.Models
#model InFlowConvertWeb.WebUI.Models.SearchControlListViewModel
#{
ViewBag.Title = "List";
}
#using (Html.BeginForm())
{
<table id="dataTable" class="table table-bordered table-hover">
<tbody>
#{int searchControlIndex = 0;}
#foreach (SearchControl searchControl in Model.SearchControls)
{
switch (searchControl.ControlType)
{
case SearchControl.ControlTypes.TextBox:
{
<tr>
<td>
#Html.Label(searchControl.FieldName, new { #class = "col-md-12 control-label" })
</td>
<td>
#Html.TextBoxFor(x =>x.SearchControls[searchControlIndex].SearchValue)
#Html.HiddenFor(x =>x.SearchControls[searchControlIndex].DataTable)
#Html.HiddenFor(x =>x.SearchControls[searchControlIndex].FieldName)
</td>
</tr>
break;
}
}
searchControlIndex += 1;
}
</tbody>
</table>
<div class="col-md-2">
<h2> <input type="submit" value="Submit Selections" /> </h2>
</div>
}

Related

How to deal with checkboxes in html page?

I want to get the output as single row like group name and visible or not. but in my scenario i am getting different output .
enter image description here
Here is my html code.
#model List<F3CentricMVCApp.Areas.KnowledgeBox.Models.GroupResponse>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<div class="col-12">
<table id="tblSectionGroups" class="table responsive table-striped" bPaginate="true">
<thead>
<tr>
<th width="95%">Groups</th>
<th width="5%" class="no-sort"></th>
</tr>
</thead>
<tbody>
#if (#ViewBag.UnAssidnedGroups is not null)
{
#foreach (var item in Model)
{
<tr>
<td>#item.Name</td>
#foreach (var unassinedGroup in ViewBag.UnAssidnedGroups)
{
#if (#unassinedGroup.GroupId == #item.Id)
{
<td>
<input type="checkbox" class="chkSectionVisibility" />
</td>
}
else
{
<td>
<input type="checkbox" class="chkSectionVisibility" checked="checked" />
</td>
}
}
</tr>
}
}
</tbody>
</table>
</div>
<script>
$('#tblSectionGroups').DataTable({
"bLengthChange": false,
"pageLength": 5,
"bPaginate": true,
"stripeClasses": [],
"info": false,
language: {
searchPlaceholder: "Type to filter list",
search: ""
},
"order": [],
"columnDefs": [{
"targets": 'no-sort',
"orderable": false,
}]
});
</script>
<div class="col-md-12 text-right">
<button type="button" class="btn btn-custom" tabindex="3" id="btnSave">Save</button>
</div>
Single checkbox for each group in a row is my requirement. any body can guide me how to deal with two collections in a code which is going through 2 foreach statements. but the logic should not be disturbed after all.
Update your foreach code as below i.e.
#if (#ViewBag.UnAssidnedGroups is not null)
{
#foreach (var item in Model)
{
int isUnassigned = 0;
<tr>
<td>#item.Name</td>
#foreach (var unassinedGroup in ViewBag.UnAssidnedGroups)
{
#if (#unassinedGroup.GroupId == #item.Id)
{
<td>
<input type="checkbox" class="chkSectionVisibility" />
</td>
// Setting.
isUnassigned++;
}
}
if (isUnassigned <= 0)
{
<td>
<input type="checkbox" class="chkSectionVisibility" checked="checked" />
</td>
}
</tr>
}
}
Hopefully this will solve your issue.

Server Error in '/' Application. ASP.Net MVC Visual Studio 2019

Whenever I run the program, it works perfectly. However, as soon as I hit the "Login" button it tells me
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /LoginController/Authorize
I checked everything and the spelling is correct. I am new to this and cannot figure out what I am doing wrong. Any guidance would be highly appreciated it.
Inside of the App_Start folder I have my RouteConfig.cs file. It contains the following:
namespace CoffeeShop_Web_App
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "LoginController", action = "Index", id = UrlParameter.Optional }
);
}
}
}
I have one controller which is my LoginController.cs which contains the following.
namespace CoffeeShop_Web_App.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Authorize()
{
return View();
}
}
}
Lastly, my only view Index.cshtml which contains the following.
#model CoffeeShop_Web_App.Models.OwnerLogin
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<style>
#login-div {
position: absolute;
left: 40%;
top: 40%;
border: 1px solid #ccc;
padding: 10px 10px;
}
</style>
</head>
<body>
<div id="login-div">
#using (Html.BeginForm("Authorize", "LoginController", FormMethod.Post))
{
<table>
<tr>
<td></td>
<td style="text-decoration:underline">Coffee Shop</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.USERNAME)
</td>
<td>
#Html.EditorFor(model => model.USERNAME)
</td>
</tr>
<tr>
<td></td>
<td>#Html.ValidationMessageFor(model => model.USERNAME)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.PASSWORD)
</td>
<td>
#Html.EditorFor(model => model.PASSWORD)
</td>
</tr>
<tr>
<td></td>
<td>#Html.ValidationMessageFor(model => model.PASSWORD)</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="name" value="Login" />
<input type="reset" name="name" value="Clear" />
</td>
</tr>
</table>
}
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</body>
</html>
Your form is posting back to the Authorize method of LoginController controller:
#using (Html.BeginForm("Authorize", "LoginController", FormMethod.Post))
You don't have to specify controller suffix for the name of the controller. The following should fix it:
#using (Html.BeginForm("Authorize", "Login", FormMethod.Post))
Also you did the same mistake when setting up the routing too:
defaults: new { controller = "LoginController", action = "Index",
id = UrlParameter.Optional }
which should have been just:
defaults: new { controller = "Login", action = "Index",
id = UrlParameter.Optional }

Dynamically building part a Razor view - getting end tag issue

I'm dynamically building part of a Razor view based upon the number of entries in a model list.
At design time, I get a little red dot before this ending div in this if:
#if (lastOne == 'n')
{
</div> #* Finishes the row. *#
}
And at design time, I'm getting an "End tag is missing a start tag" at the bottom.
How do I resolve that? How do I build this dynamically if I get that?
At run-time, as expected, I get: Encountered end tag "div" with no matching start tag. Are your start/end tags properly balanced?
Here's the .cshtml file (the view):
<h2>Test</h2>
#model GbngWebClient.Models.UserProfileForMaintVM
#using (Html.BeginForm("UpdateUserProfile", "UserProfiler", FormMethod.Post))
{
<div style="margin-top:10px;"></div>
<div class="panel panel-default">
<div class="panel-heading aboutyou">It's All About You!</div>
<br />
<h5 class="single">General</h5>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
#Html.LabelFor(model => model.UserProfileSingleVM.WhoIAmDescr)
#Html.TextAreaFor(model => model.UserProfileSingleVM.WhoIAmDescr, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserProfileSingleVM.WhoIAmDescr, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
#Html.LabelFor(model => model.UserProfileSingleVM.ThinkingDescr)
#Html.TextAreaFor(model => model.UserProfileSingleVM.ThinkingDescr, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserProfileSingleVM.ThinkingDescr, "", new { #class = "text-danger" })
</div>
</div>
<br />
</div>
<div class="panel-body">
#{
var lastOne = 'n';
var colCount = 1;
}
#for (var i = 0; i < Model.UserProfileMultiList25.Count; i++)
{
if (colCount == 1)
{
<div class="row">
}
<div class="col-md-3">
#Html.LabelFor(Model => Model.UserProfileMultiList25[i].Description))
#Html.CheckBoxFor(Model => Model.UserProfileMultiList25[i].SelectedSwitch, new { #class = "form-control" })
</div>
if (colCount == 3)
{
</div> #* Finishes the row. *#
colCount = 1;
lastOne = 'y';
}
else
{
colCount += 1;
}
}
#if (lastOne == 'n')
{
</div> #* Finishes the row. *#
}
</div> #* Finishes the panel. *#
<div class="panel-body">
<div class="row">
<div class="form-group">
<div class="col-md-offset-0 col-md-12">
#* Submit button. *#
<input type="submit" value="Save" class="btn btn-info" />
</div>
</div>
</div>
</div>
</div>
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
It works but does not surround it with a:
<div class="row">....</div>.
Gets the job done:
#for (var i = 0; i < Model.UserProfileMultiList25.Count; i++)
{
<div class="col-md-3">
<div>
#Html.CheckBoxFor(Model => Model.UserProfileMultiList25[i].SelectedSwitch, new { #class = "form-control" })
<label>
#Html.DisplayFor(Model => Model.UserProfileMultiList25[i].Description)
#Html.HiddenFor(Model => Model.UserProfileMultiList25[i].SelectionId)
#Html.HiddenFor(Model => Model.UserProfileMultiList25[i].ProfileCategoryId)
</label>
</div>
</div>
}
You are declaring colCount inside of your loop, and it's getting initialized to 1 each time. I'm guessing what you mean to do is to declare and initialize it outside the loop so it's an actual counter:
#{
var lastOne = 'n';
var colCount = 1;
}
#for (var i = 0; i < Model.UserProfileMultiList25.Count; i++)
{
if (colCount == 1)
{
<div class="row">
}
<div class="col-md-3">
#Html.LabelFor(Model => Model.UserProfileMultiList25[i].Description))
#Html.CheckBoxFor(Model => Model.UserProfileMultiList25[i].SelectedSwitch, new { #class = "form-control" })
</div>
if (colCount == 3)
{
</div> #* Finishes the row. *#
colCount = 1;
lastOne = 'y';
}
else
{
colCount++;
}
}
#if (lastOne == 'n')
{
</div> #* Finishes the row. *#
}

How to make MVC Controller have option to reload or not reload based the button selected on Html.BeginForm

I am sending the model values with attachments,I have two buttons below the form "Save And Close" and "Save"..when I click on "Save and Close" I want it to reload and navigate to a different controller and action but when I click on "Save" I want it to remain on the same page Please assist me I tried using ajax,BeginForm it doesn't send out files to my controller when I google they told me about using formData which doesn't work on my case since my application must strictly work on iE.
Hi Below is my Html.BeginForm
<div class="grid_section">
<div class="grid_heading">
<span class="font_red font_bold">Activity Detail</span>#*#ViewBag.changeTitle*#
</div>
<div class="grid_space">
#using (Html.BeginForm("ActivitySave", "ActivityMaintenance", FormMethod.Post,
new
{
enctype = "multipart/form-data",
name = "frmSaveActivity",
id = "frmSaveActivity",
onsubmit = "return SubmitfrmSaveActivity()"
}))
{
#Html.HiddenFor(model => model.ActivityId)
#Html.HiddenFor(model=>model.OrderNumber)
if (Model.FirstDocumentPicture != null)
{
<input type="hidden" value="data:image/gif;base64,#Convert.ToBase64String(Model.FirstDocumentPicture)" id="firstImg" />
}
if(Model.SecondDocumentPicture != null)
{
<input type="hidden" value="data:image/gif;base64,#Convert.ToBase64String(Model.SecondDocumentPicture)" id="secondImg" />
}
if(Model.DocumentVideo != null)
{
<input type="hidden" value="#Model.DocumentVideo" id="VideoFromDb" />
}
<table>
<tbody>
<tr>
<td></td>
<td>#ViewBag.changeTitle </td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Process)</td>
<td>
#ViewBag.CurrentProcess
#Html.ValidationMessageFor(model => model.Process)
</td>
</tr>
#*<tr>
<td>
#Html.LabelFor(model => model.OrderNumber)
</td>
<td>
#if (Model.ActivityId != 0)
{
#Html.DisplayFor(model => model.OrderNumber, new { #readonly = "readonly" })
}
else
{
<p>New</p>
}
</td>
</tr>*#
<tr>
<td>
#Html.LabelFor(model => model.ActivityName)
</td>
<td>
#Html.TextAreaFor(model => model.ActivityName, new { #class = "editForm", style = "width: 99%; height:35px" })
#Html.ValidationMessageFor(model => model.ActivityName)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Input)
</td>
<td>
#Html.TextAreaFor(model => model.Input, new { #class = "editForm", style = "width: 99%; height:35px" })
#Html.ValidationMessageFor(model => model.Input)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Output)
</td>
<td>
#Html.TextAreaFor(model => model.Output, new { #class = "editForm", style = "width: 99%; height:35px" })
#Html.ValidationMessageFor(model => model.Output)
</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Responsible)</td>
<td>
#Html.TextBoxFor(model => model.Responsible, new { style = "width: 99%; ", #class = "editForm" })
#Html.ValidationMessageFor(model => model.Responsible)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.SHEQAspects)
</td>
<td>
#Html.TextAreaFor(model => model.SHEQAspects, new { #class = "editForm", style = "width: 99%; height:35px " })
#Html.ValidationMessageFor(model => model.SHEQAspects)
</td>
</tr>
</tbody>
</table>
<br />
<div class="square">
Image Caption: #Html.TextAreaFor(model => model.FirstDocumentPictureCaption, new { #class = "editForm", style = "width: 60%; height:18px " })<br /><br />
Upload Image : <input style="width: 60%;" type="file" name="uploadedLogo" id="firstfile" accept="*" #*onchange="DocumentSizeCheck()"*# /> <br /><br />
<div class="gridContent">
<output id="firstfileList" class="gridTable">
</output>
</div>
</div>
<div class="square">
Image Caption: #Html.TextAreaFor(model => model.SecondDocumentPictureCaption, new { #class = "editForm", style = "width: 60%; height:18px " })<br /><br />
Upload Image : <input style="width:60%;" type="file" name="uploadedLogo" id="Secondfile" accept="*" #*onchange="DocumentSizeCheck()"*# /> <br /><br />
<div class="gridContent">
<output id="SecondFileList" class="gridTable">
</output>
</div>
</div>
<div class="square">
Video Caption:#Html.TextAreaFor(model => model.DocumentVideoCaption, new { #class = "editForm", style = "width: 60%; height:18px " })<br /><br />
Upload Video :<input style="width:60%;" type="file" name="uploadedLogo" id="Videofile" accept="*" /><br /><br />
<div class="gridContent">
<div controls class="video gridTable" >
<object classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" width="480" height="330" codebase="http://www.microsoft.com/Windows/MediaPlayer/">
<param id="video_here" name="Filename" value="#Model.DocumentVideo">
<param name="AutoStart" value="false">
<param name="ShowControls" value="true">
<param name="BufferingTime" value="2">
<param name="ShowStatusBar" value="true">
<param name="AutoSize" value="true">
<param name="InvokeURLs" value="false">
<embed id="video_here"src="#Model.DocumentVideo" type="application/x-mplayer2" autostart="1" enabled="1" showstatusbar="1" showdisplay="1" showcontrols="1" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" CODEBASE="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,0,0,0" width="480" height="360"></embed>
</object>
</div>
</div>
</div>
<div class="buttonsBelow" style="margin-right: 50px;margin-top: 470px;">
<input class="submitOnNew" type="button" value="Save" />
<input id="btnSave" type="submit" value="Save and Close" />
<input type="button" value="Cancel" onclick="CancelfrmSaveActivity()" />
</div>
}
</div>
</div>
And the MVC C# controller
[HttpPost]
public ActionResult ActivitySave(ActivityModel model, IEnumerable<HttpPostedFileBase> uploadedLogo)
{
try
{
if (Cache.SelectedModule() != null && Cache.SelectedModule() is ProcessModel)
searchProcessId = ((ProcessModel)Cache.SelectedModule()).Id;
byte[] firstImage = null;
byte[] SecondImage = null;
string DocVideo = "";
List<byte[]> dataFiles = new List<byte[]>();
foreach (HttpPostedFileBase i in uploadedLogo)
{
if (i != null)
{
//var test = new Test.ImpersonateUser();
//test.Impersonate("LINDE", "za035d", "Pass1234");
var files = uploadedLogo.ToList();
var filesd = uploadedLogo.ToList();
string FilePath = "";
string savePath = #"\\MLGJNB01NETFIL1\ClientApplicationData\AfroxHQMS\";
string filename = "";
// if directory doesnt exists, create it
if (!System.IO.Directory.Exists(savePath))
System.IO.Directory.CreateDirectory(savePath);
byte[] fileData = new byte[i.InputStream.Length];
i.InputStream.Read(fileData, 0, fileData.Length);
FilePath = Path.GetFileName(i.FileName);
// get file extention
int pos = FilePath.LastIndexOf(".");
if (pos > 0)
{
string ext = FilePath.Substring(FilePath.LastIndexOf("."));
filename = string.Format(#"{0}" + ext, Guid.NewGuid());
}
else
filename = Guid.NewGuid().ToString();
//i.SaveAs(savePath + filename);
i.SaveAs(savePath + FilePath);
if (files[0] != null && (filesd[0] == i))
{
firstImage = fileData;
}
if (files[1] != null && (filesd[1] == i))
{
SecondImage = fileData;
}
if (files[2] != null && (filesd[2] == i))
{
string initPath = "file://MLGJNB01NETFIL1/ClientApplicationData/AfroxHQMS/" + FilePath;
DocVideo = initPath;
}
}
}
ActivityProvider.SaveActivity(model.ActivityId, searchProcessId, model.ActivityName, model.OrderNumber,
model.Input, model.Output, model.Responsible, model.SHEQAspects, firstImage, SecondImage, DocVideo,model.FirstDocumentPictureCaption,model.SecondDocumentPictureCaption,model.DocumentVideoCaption);
return View("_ActivityDetail", PopulateActivities(model.ActivityId));
}
catch (SecurityException error)
{
return null;
}
}

put Button and text box in parallel

Im trying to put the following button and text box in parallel that the button in the left side and the text box in the right ,I try with span and margin but currently the text box is under the button ,how should I do that>
<span>
<input type="submit" id="Connect" style="margin-left: 195px; width: 150px;" class="btn action-but" />
<div class="form-group">
#Html.LabelFor(model => model.Service, new { #class = "col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Service, new { #style = "width: 700px;" })
#Html.ValidationMessageFor(model => model.Service)
</div>
</div>
</span>
If i understand good you want to show something like this:
[button] [label text errors]
To do that a easy way is to add in style: display: inline-block;
The result, based on your code will be something like this
<span>
<input type="submit" id="Connect" style="display: inline-block;margin-left: 195px; width: 150px;" class="btn action-but" />
<div class="form-group" style="display: inline-block;">
#Html.LabelFor(model => model.Service, new { #class = "col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Service, new { #style = "width: 700px;" })
#Html.ValidationMessageFor(model => model.Service)
</div>
</div>
</span>
You can find in JsFiddle a demo of this: http://jsfiddle.net/pR6Wg/
I think you are looking for vertical form. look at this example bootstrap vertical form
Razor example
<form class="form-inline" role="form">
<div class="form-group">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">#</div>
#Html.TextBoxFor(model => model.Service, new { #class="form-control", #placeholder="Enter email" })
</div>
</div>
</form>
Remove margin-left: 195px of submit button add add it inside .col-md-2 before the label.
and change <div class="col-md-10"> to <div class="col-md-8">
DEMO
CODE
<span>
<div class="form-group">
<div class="col-md-2">
<input type="submit" id="Connect" style=" width: 150px;" class="btn action-but" />
</div>
#Html.LabelFor(model => model.Service, new { #class = "col-md-2" })
<div class="col-md-8">
#Html.TextBoxFor(model => model.Service, new { #style = "width: 700px;" })
#Html.ValidationMessageFor(model => model.Service)
</div>
</div>
</span>
Why don't use a table? Or you want to do it with div's?
<table class="col-md-10">
<td>
<tr>
#Html.TextBoxFor(model => model.Service, new { #style = "width: 700px;" })
</tr>
</td>
<td>
<tr>
#Html.ValidationMessageFor(model => model.Service)
</tr>
</td>
</table>
Hope it helps! =)