This is now solved, leaving it here for others to find
I have tried to find the answer to the question, although I'm fairly new to this, I could have had the answer staring me in the face. So I do apologise.
I have created a MVC web app which basically saves a selection on a radio button to a cookie and then show's the selection on the next page. I think I'm close, but could you look at the code below and see why I can't get it to show the radio button text? Thanks in advance!
This is my controller;
public IActionResult WriteCookies(string submitOption, bool isPersistent)
{
if (isPersistent)
{
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(14);
Response.Cookies.Append("setting", submitOption, options);
}
else
{
Response.Cookies.Append("setting", submitOption);
}
ViewBag.Message = "Turn Registered!";
return View("Meoryou");
}
public IActionResult ReadCookies()
{
var cookieVal = Request.Cookies["setting"];
ViewBag.submitOption = cookieVal;
return View("MeoryouViewReturn");
}
Webviews;
<div class="cookieCreator">
<form asp-action="WriteCookies" asp-controller="Meoryou">
<input type="radio" value="Sam" name="submitOption"> Sam<br />
<input type="radio" value="Chris" name="submitOption"> Chris<br />
<input type="radio" value="Other" name="submitOption"> Other<br />
<input type="checkbox" name="isPersistent" value="true" /> Save for 14days?<br />
<div style="color: black;">
<input type="submit" name="submitOption" value="Write Cookie" />
</div><br />
</form>
<h4>#ViewBag.Message</h4>
<h4>
<a class="btn-lg" asp-action="ReadCookies" asp-controller="Meoryou">
See whose turn it is.<br />
</a>
</h4>
Webview Return;
<div>
Turn: #ViewBag.submitOption
</div>
Related
Newbie question, please be kind.
I have this Index.cshtml page in C# MVC application. When the page is rendered, the last button is checked. How do I make the first button (All) set to checked instead?
I am reading thru the "similar questions", but none seem to address my question. Please help. Thank you in advance if you can explain this to me.
<h1>#ViewBag.title</h1>
<form action="/list/index" method="post">
<h2>Search by:</h2>
<p>
#foreach (var column in ViewBag.columns)
{
<span>
<input type="radio" name="searchType" id="#column.Key" value="#column.Key" checked="#column.Key == 'all'" />
<label for="#column.Key">#column.Value</label>
</span>
}
</p>
<p>
<label for="searchTerm">Keyword:</label>
<input type="text" name="searchTerm" id="searchTerm" />
</p>
<input type="submit" value="Search" />
</form>
<hr />
#if (ViewBag.service != null)
{
<table>
#foreach (var srv in ViewBag.service)
{
<tr>
<td>
<p>Provider: #srv.Provider.Name</p>
<p>Location: #srv.Location.Address</p>
<p>Category: #srv.Category.Name</p>
#* <p>Tag: #service.Tag</p>
<p>Keyword: #service.Keyword</p>*#
</td>
</tr>
}
</table>
}
In one condition:
<input type="radio" name="searchType" id="#column.Key" value="#column.Key" #(column.Key == 'all' ? "checked" : " ") />
Checked or not checked?
You can just use checked for checked any radio button:
<input type="radio" checked />
For conditionally check any of your radio button, use this:
#if(column.Key == 'all'){
<input type="radio" name="searchType" id="#column.Key" value="#column.Key" checked />
}else{
<input type="radio" name="searchType" id="#column.Key" value="#column.Key" />
}
I'm writing an application using Blazor server side and .Net 5. I want when I write text in the search box it will show results in new divs. However, the search results are not displayed. When I debug the code from service works fine.
#page "/"
#using MovieSearch.Service
#using MovieSearch.Data
#using MovieSearch.Helpness
#inject IOMDbService service
<div class="movie-search">
<div class="search-container">
<form action="/">
<input type="text" placeholder="Find a movie" #bind-value="#searchTerm" />
<button type="submit" #onclick="FindMovies"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
<div class="movies">
#if(moviesResult != null)
{
if(!moviesResult.Success)
{
foreach(var error in moviesResult.Errors)
{
<p>#error.Message</p>
}
}
else
{
foreach(var movie in moviesResult.Value)
{
<div class="movie">
<p>#movie.Title</p>
<img src="#movie.Poster" />
</div>
}
}
}
</div>
#code
{
private string searchTerm;
private Result<IEnumerable<Movie>> moviesResult;
async Task FindMovies()
{
moviesResult = await service.FindMovies(searchTerm);
}
}
What can I do to view the results?
Try changing this part of your code from
<form action="/">
<input type="text" placeholder="Find a movie" #bind-value="#searchTerm" />
<button type="submit" #onclick="FindMovies"><i class="fa fa-search"></i></button>
</form>
to just this
<input type="text" placeholder="Find a movie" #bind-value="#searchTerm" />
<button #onclick="FindMovies"><i class="fa fa-search"></i></button>
So in other words, remove the form tags, as well as removing the type on the button. I believe that blazor is now actually trying to post the form to whatever action you specified in the form as opposed to the onclick handler you assigned to your button.
Update :
This is an SPA app.So it's having js file also for supporting the submit button.So I think problem is on it.Could you tell me how to modify it to support multiple kind of submit buttons ? At this moment I think it supports only for a single submit button.That is why it always get the first form's hidden field value I think.Thanks.
JS
var $loginForm = $('.login-form');
$loginForm.submit(function (e) {
e.preventDefault();
if (!$('.login-form').valid()) {
return;
}
abp.ui.setBusy(
null,
abp.ajax({
contentType: app.consts.contentTypes.formUrlencoded,
url: $loginForm.attr('action'),
data: $loginForm.serialize()
})
);
});
UI
VM
public class LoginViewModel
{
public string TenancyName { get; set; }
[Required]
public string UsernameOrEmailAddress { get; set; }
[Required]
public string Password { get; set; }
public bool RememberMe { get; set; }
}
CompanyLoginFormViewModel VM :
public class CompanyLoginFormViewModel
{
public LoginViewModel LoginViewModel { get; set; }
public List<TenantListDto> Tenants { get; set; }
}
*.cshtml page
#{
var companyLoginFormViewModel = TempData["CompanyLoginFormViewModel"] as CompanyLoginFormViewModel;
}
#foreach (var tenant in companyLoginFormViewModel.Tenants)
{
<form class="login-form" action="#Url.Action("Login")?returnUrl=#ViewBag.ReturnUrl" name="companyLoginForm" method="post">
<input type="hidden" name="usernameOrEmailAddress" value="#companyLoginFormViewModel.LoginViewModel.UsernameOrEmailAddress" />
<input type="hidden" name="password" value="#companyLoginFormViewModel.LoginViewModel.Password" />
<input type="hidden" name="rememberMe" value="true" />
<input type="hidden" name="companyUrl" value="true" />
<input type="hidden" name="tenancyName" value="#tenant.TenancyName" />
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">#L("LogIn")</button>
</div>
</div>
</form>
}
Generated html
<form class="login-form" action="/Account/Login?returnUrl=/Application" name="companyLoginForm" method="post" novalidate="novalidate">
<input type="hidden" name="usernameOrEmailAddress" value="fake#gmail.com">
<input type="hidden" name="password" value="fake">
<input type="hidden" name="rememberMe" value="true">
<input type="hidden" name="companyUrl" value="true">
<input type="hidden" name="tenancyName" value="Asset_Management">
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">Log in</button>
</div>
</div>
</form>
<form class="login-form" action="/Account/Login?returnUrl=/Application" name="companyLoginForm" method="post" novalidate="novalidate">
<input type="hidden" name="usernameOrEmailAddress" value="fake#gmail.com">
<input type="hidden" name="password" value="fake">
<input type="hidden" name="rememberMe" value="true">
<input type="hidden" name="companyUrl" value="true">
<input type="hidden" name="tenancyName" value="Associates">
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">Log in</button>
</div>
</div>
</form>
<form class="login-form" action="/Account/Login?returnUrl=/Application" name="companyLoginForm" method="post" novalidate="novalidate">
<input type="hidden" name="usernameOrEmailAddress" value="fake#gmail.com">
<input type="hidden" name="password" value="fake">
<input type="hidden" name="rememberMe" value="true">
<input type="hidden" name="companyUrl" value="true">
<input type="hidden" name="tenancyName" value="ALL">
<div class="row margin-top-10">
<div class="col-xs-3">
<button type="submit" class="btn btn-success uppercase">Log in</button>
</div>
</div>
</form>
Post method
[HttpPost]
public virtual async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl = "", string returnUrlHash = "", bool companyUrl = false)
{
CheckModelState();
// removed for clarity
}
Question : Even though I have press the 2nd submit button,it always send the tenancyName as first submit button's value.That is Asset_Management.Could you tell me why ? Thanks.
Your problem is with the script.
var $loginForm = $('.login-form');
is a collection of all your forms, but
data: $loginForm.serialize(),
will only serialize the first one, so you always posting the vales of the first form. Modify the script to handle the buttons .click() event and get its associated form
$('.btn-success').click(function(e) {
e.preventDefault(); // if you makes the button type="button" this is not required
var form = $(this).closest('.login-form');
if (!form.valid()) {
return;
}
abp.ui.setBusy(
null,
abp.ajax({
contentType: app.consts.contentTypes.formUrlencoded,
url: form.attr('action'),
data: form.serialize()
})
);
});
Why do you even have <form> and <button> at all?
Why not create links in your foreach loop, something like this:
#Html.ActionLink("Login for " + tenant.Name, "LoginAction", new {Id=tenant.Id})
You can style these links all blue and pretty as you like using CSS afterwards.
Update1, you can pass parameters to your controller using the anonymous object. Do you see how I am passing Id? Your Action will need to accept id, see this answer: passing multiple parameters in #html.actionlink()
Update2, passing username and password like this is very bad practice. You are exposing secure credentials to the view. You should forward the user to the login page with username + password input boxes where the user will login.
View:
#using (#Html.BeginForm("Show", "test", FormMethod.Post))
{
<fieldset>
<table >
<tr>
<td>
#Html.LabelFor(model=> model.Show)
</td>
<td>
#Html.TextBox("txtvalue", null)
</td>
</tr>
</table>
<input type="button" value="Show" onclick = "#("location.href='"+ #Url.Action("Show", "test")+"'" )" />
<input type="button" value="Go" onclick ="#("location.href='"+ #Url.Action("Go", "test")+"'" )"/>
</fieldset>
}
and two action methods in the controller,
public ActionResult Show(string txtvalue)
{
...
}
public ActionResult Go(string txtvalue)
{
...
}
based on which button been click , it should go to the corresponding action method and pass the value of the textbox.
Can anyone suggest me the way to do it. I wrapping my head around couldn't figure out.
Try this,
<input type="button" value="Show" onclick = "location.href='#Url.Action("Show", "Foo")'"/>
<input type="button" value="Go" onclick = "location.href='#Url.Action("Go", "Foo")'"/>
UPDATE:
As type="button" does not submit the values in the form, its not directly possible to do what you have asked, the better idea is to Identify the Button that has been clicked in the controller method as show in this link
Try this
<input type="button" value="Show" onclick="location.href='<%: Url.Action("Show", "Controller") %>'" />
<input type="button" value="Go" onclick="location.href='<%: Url.Action("Go", "Controller") %>'" />
Try something like:
<input type="button" value="Show" onclick="location.href='<%:Url.Action("Show", "ControllerName")%>'"/>
<input type="button" value="Go" onclick="location.href='<%:Url.Action("Go", "ControllerName")%>'"/>
If you are posting more form data you can use Ajax, see Making a Simple Ajax call to controller in asp.net mvc
I have a Form where I want to limit the Data from my Drop Downlist when the checkbox is checked
So when the Is Primary checkbox is Checked , There will be no 2 Email address that the Is Primary is Both True !! That is what i Want to Prevent
So that When i Save theres a Message window that will Appear and Let the user know that he/she checked the checkbox for the Same Drop Down Value
using (Html.BeginForm("Save", "Worker", FormMethod.Post, new { id = "contactForm" }))
{
<input type="hidden" id="workerId" name="workerId" value="#workerId" />
<p>
<label for="ddlContactType">
Contact Type</label>
<span>
#Html.DropDownList("ddlContactType", new SelectList(ViewBag.ContactTypeList, "ID", "Display_Value", workerContactType), "[Please Select]",
new Dictionary<string, object>
{
{"class","validate[required] inputLong"}
})
</span>
</p>
<p>
<label for="txtContactValue">
Contact Value</label>
<span>
<input type="text" id="txtContactValue" name="txtContactValue" class="validate[required] inputLong" value="" />
<input type="checkbox" name="chkWorkerIsPrimary" id="chkWorkerIsPrimary" value="true"
checked="checked" />
<label>
Is Primary?</label>
</span>
</p>
<p>
<span>
<input type="submit" id="btnAdd" class="styledButton" value="Add" />
</span>
</p>
}
</div>
I need the Validation written in Javascript or Jquery but i dont know how to start :(
Thanks
This is where you begin.
$('#chkWorkerIsPrimary :checkbox').click(function() {
var $this = $(this);
if ($this.is(':checked')) {
// do something
}
else {
//do something else
}
});