MVC Basic - how to get html button in URL - c#

I'm new in MVC.
I have simple HTML website where I have two three inputs
input to write email adress
one checkbox
button
I have one HomeController which have on method
[HttpGet]
public ActionResult Index()
{
return View();
}
I want to generate method [HttpPost] after I click the button.
Now after I am click inputbutton in my Url I have just one change
Before click
http://localhost:52254/Home/Index
and after
http://localhost:52254/Home/Index?
There is a form
<form>
<div class="col-xs-3">
<input type="email" class="form-control" id="email" placeholder="Wpisz adres email">
</div>
<br />
<label class="checkbox-inline">
<input type="checkbox" />
</label>
<br />
<a href="/Controller/View">
<input type="submit" value="Sign" class="btn btn-primary"/>
</a>
</form>

Change The Code Like This
#using (Html.BeginForm())
{
<div class="col-xs-3">
<input type="email" class="form-control" id="email" placeholder="Wpisz adres email">
</div>
<br />
<label class="checkbox-inline">
<input type="checkbox" />
</label>
<br />
<a>
<input type="submit" value="Sign" class="btn btn-primary"/>
</a>
}

Related

Passing model from get method to a post nulls the model

When I pass model to the view on the post method the ProductId and UserId get nulled.
[HttpGet]
public async Task<IActionResult> AddReview(int id)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var model = new AddReviewViewModel()
{
ProductId = id,
UserId = userId
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> AddReview(AddReviewViewModel addReviewViewModel)
{
if (!ModelState.IsValid)
{
return View(addReviewViewModel);
}
//...
}
Here is how I call the post method.
<div class="row">
<div class="col-sm-12 offset-lg-2 col-lg-8 offset-xl-3 col-xl-6">
<form asp-action="AddReview" method="post">
<div class="mb-3">
<label asp-for="#Model.Comment" class="form-label">Comment</label>
<input asp-for="#Model.Comment" class="form-control" aria-required="true" />
<span asp-validation-for="Comment" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="#Model.Rating" class="form-label">Rating</label>
<input asp-for="#Model.Rating" class="form-control" aria-required="true" />
<span asp-validation-for="Rating" class="text-danger"></span>
</div>
<div class="mb-3">
<input class="btn btn-primary" type="submit" value="Submit Review" />
</div>
</form>
</div>
</div>
I have done something like this while adding a new product but I haven't had any problem.
You have to return the data. It needs to make a round-trip. This is typically done with hidden input fields.
<input type="hidden" id="ProductId" name="ProductId" value="#Model.ProductId">
<input type="hidden" id="UserId" name="UserId" value="#Model.UserId">
Full example
<form asp-action="AddReview" method="post">
<input type="hidden" id="ProductId" name="ProductId" value="#Model.ProductId">
<input type="hidden" id="UserId" name="UserId" value="#Model.UserId">
<div class="mb-3">
<label asp-for="#Model.Comment" class="form-label">Comment</label>
<input asp-for="#Model.Comment" class="form-control" aria-required="true" />
<span asp-validation-for="Comment" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="#Model.Rating" class="form-label">Comment</label>
<input asp-for="#Model.Rating" class="form-control" aria-required="true" />
<span asp-validation-for="Rating" class="text-danger"></span>
</div>
<div class="mb-3">
<input class="btn btn-primary" type="submit" value="Submit Review" />
</div>
</form>
If your version supports taghelpers you can also write:
<input type="hidden" asp-for="ProductId">
<input type="hidden" asp-for="UserId">
Or using the HtmlHelper:
#Html.HiddenFor(m => m.ProductId)
#Html.HiddenFor(m => m.UserId)
In all cases, make sure you add this inside the form.

ASP.Net Core MVC Disable validation when a specific button is pressed

I have 2 buttons on my form, a Submit and Save button. I want to be able to skip all validation when a user clicks the Save button. I've tried adding class="cancel", formnovalidate, formnovalidate="formnovalidate", disableValidation="true" to the Save button but none of them worked. Any help would be wonderful! I'm using ASP.NET Core 3.1.
Form
<form asp-action="Request">
...
...
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" class="btn btn-secondary" />
</form>
<partial name="_ValidationScriptsPartial" />
Firstly,you need to know,if you use _ValidationScriptsPartial,it would generate the html like below:
Generate cshtml from:
<input asp-for="MyDate" class="form-control" />
to:
<input class="form-control" type="date" data-val="true"
data-val-required="The MyDate field is required."
id="MyDate" name="MyDate" value="">
formnovalidate and class="cancel" attribute could skip the validation in client side,but could not skip validation in server side.
To fix such issue,you could clear model state:
1.Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(add formnovalidate to save input):
#model Test
<form asp-action="Request">
<div>
Name:<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div>
Id:<input asp-for="Id" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" formnovalidate class="btn btn-secondary" />
</form>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
3.Action:
[HttpPost]
public IActionResult Request(Test test)
{
if (!ModelState.IsValid)
{
ModelState.Clear();
return View("Index");
}
return View("Index");
}
4.Result:
<form asp-action="Request">
...
...
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" class="btn btn-secondary cancel" />
</form>
#section Scripts{
<partial name="_ValidationScriptsPartial" />
}

Post Async without Redirecting in Razor Pages Web Application

I am trying to make a social networking app, where users can react to posts. But every time someone reacts I need to be able to post the reaction directly to the model without redirecting.
Here is my code so far (with redirecting):
Model:
[BindProperty]
public Models.Table Table { get; set; }
public async Task<IActionResult> OnPostReactAsync(int t)
{
var reaction = new Models.Table
{
Reaction = Table.Reaction,
PostId = t,
UserName = _userManager.GetUserName(User)
};
_context.Table.Add(reaction);
await _context.SaveChangesAsync();
return Redirect("./Index");
}
View:
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<input name="t" value="#item.ID" class="form-control" style="display:none;" />
</div>
<div class="form-group">
<input asp-for="Table.Reaction" id="#item.ID x" type="radio" value="true" onclick="document.getElementById('cal').click()" />
<label class="r good" for="#item.ID x"></label>
<input asp-for="Table.Reaction" id="#item.ID y" type="radio" value="false" onclick="document.getElementById('cal').click()" />
<label class="r bad" for="#item.ID y"></label>
</div>
<div class="form-group">
<input type="submit" id="cal" asp-page-handler="React" value="submit" style="display:none;" class="btn btn-default" />
</div>
</form>

Firing 'click' event on input submit without ID or name?

I am trying to auto-fill a form on a webpage using .NET's web browser int he C# language. I need to fire the submit button but it doesn't have a name or ID, all it has is a type and value.
The type is equal to "submit" and the value is equal to "Sign In"
Heres how I did it for Sign Up:
webBrowser1.Document.GetElementById("email").InnerText = email;
webBrowser1.Document.GetElementById("password").InnerText = password;
webBrowser1.Document.GetElementsByTagName("input")["register"].InvokeMember("click");
But this time, the submit button doesn't have a name, can someone guide me in the right direction to getting an element by its type or even better, value?
HTML:
<form accept-charset="utf-8" method="post">
<div class="field">
<label for="email">Email or Username</label> <span class="required">*</span> <input class="email" id="email" name="email" size="32" type="text">
</div>
<div class="field">
<label for="password">Password</label> <span class="required">*</span> <input id="password" name="password" size="16" type="password">
<p class="tip">I don't know my password</p>
</div>
<div class="field">
<input id="persistent_hidden" name="persistent" type="hidden" value="f"> <input checked="checked" id="persistent" name="persistent" type="checkbox" value="t"> <label for="persistent">Keep me logged in</label>
</div>
<div class="submit">
<input id="redirect_path" name="redirect_path" type="hidden"> <input type="submit" value="Sign In"> or <a class="cancel" href="/">Cancel</a>
</div>
</form>
try :
foreach(HtmlElement elem in webBrowser.Document.getElementByTagName("input")) {
if (elem.GetAttribute("value") == "Sign In") {
elem.InvokeMember("Click");
}
}

Mail sending using Razor form

I have a form in my razor cshtml file. I need to send a mail on button click. How can we write the code in the same razor file?
For now my code checks the IsPost property and shows a javascript alert if true, but the alert is not showing. How can we get the values by clicking the submit button?
#inherits RazorFunction
#using System;
#{
if (IsPost)
{
<script>
alert('aaaa');
</script>
}
}
#{
<form method="post">
<div class="form_main">
<div class="col-md-6">
<input type="text" id="txtName" name="yourname" placeholder="الإسم" />
</div>
<div class="col-md-6">
<input type="text" id="txtEmail" placeholder="لبريد الإلكتروني" />
<div class="col-md-6">
<input type="text" id="txtPhone" placeholder="رقم الهاتف" />
</div>
<div class="col-md-6">
<input type="text" id="txtSubject" placeholder="الموضوع" />
</div>
<div class="col-md-12">
<input type="text" id="txtMsg" placeholder="تعليق" textmode="MultiLine" />
</div>
<div class="col-md-12">
<input type="button" id="btnSubmit" value="Submit" class="form_main_button11" data-dismiss="modal" />
<input type="button" id="btnCancel" value="Clear" class="form_main_button11" />
</div>
</div>
</div>
</form>
}
I good option to send e-mail using Razor's view engine is MvcMailer:
Sample.cshtml view:
Hello #ViewBag.Name:<br />
Welcome to MvcMailer and enjoy your time!<br />
Action to send the e-mail:
public virtual MvcMailMessage Sample()
{
ViewBag.Name = "Test";
return Populate(x =>{
x.viewName = "Sample";
x.To.Add("test#example.com");
});
}
More details on this step-by-step guide.

Categories

Resources