MVC BeginForm No Data Posted - c#

I am using MVC BeginForm with code below, i cannot get the value fpr input controls in my controller. am i doing anytyhing wrong here?
using (Ajax.BeginForm("CreateApp", "App",
new AjaxOptions { UpdateTargetId = "my-modal-dialog", OnBegin = "Dialog.Closing()", OnSuccess = "Dialog.Close()" },
new
{
#class = "appform"
}
))
{
<input id="newAppName" type="text" size="35" value="" />
#Html.TextBoxFor(model => model.Application.AppName);
<input type="submit" value="Start App" class="demo-button ui-state-default ui-corner-all" />
}
My Controller looks like this
[HttpPost]
public ActionResult CreateApp(AppContent app, string newAppName)
{
}

try changing
<input id="newAppName" type="text" size="35" value="" />
to
<input name="newAppName" type="text" size="35" value="" />

Related

Form not passing POST data to controller

I am passing in a reference to a file, and a string value cardid. For some reason when I return the result the cardid value is null. However when I view the page the <h3> header contains the string I expected. What am I doing wrong?
HTML view
<h3>#Model.CV.Id</h3>
#using (Html.BeginForm("UploadFile", "Tickets", FormMethod.Post, new { cardid=#Model.CV.Id, enctype = "multipart/form-data"}))
{
<input type="file" name="file" />
<input type="submit" value="Upload Attachment" />
}
Controller
public async Task<IActionResult> UploadFile(string cardid,IFormFile file)
{
......
string res="yay";
return Ok(new {cardid=cardid,res=res });
}
You should include cardid in your form. You are simply creating an attribute on <form>, which does nothing.
<h3>#Model.CV.Id</h3>
#using (Html.BeginForm("UploadFile", "Tickets", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<input type="hidden" name="cardid" value="#(Model.CV.Id)" />
<input type="file" name="file" />
<input type="submit" value="Upload Attachment" />
}
You could also include `cardid in the action:
Html.BeginForm("UploadFile?cardid=" + Model.CV.Id, "Tickets", FormMethod.Post...)

Passing value from textbox to controller as a parameter

So in my View I need a simple textbox like so:
<input type="text" name="CVR" placeholder="Enter CVR" required />
in the same view, at the end I have the submit button:
#Html.ActionLink("Submit", "SendMail", new { studentId = Html.ViewData.Model.StudentId, companyId = Html.ViewData.Model.CompanyId, applicationId = Html.ViewData.Model.ApplicationId, companyCVR = Model.CVR})
The data works, until the "companyCVR = Model.CVR". I am having trouble changing "companyCVR" to the text the user inputs in the textbox above.
This is my controller constructor:
public ActionResult SendMail(string studentId, string companyId, int applicationId, string companyCVR)
and technically, this should work:
contract.CVR = companyCVR;
It works when I hardcoded (contract.CVR = "12345"). My problem is passing the value from the textbox to companyCVR which I am trying to pass as a parameter to the controller.
How can I solve this?
It would probably be easier if you use a <form>. Something like:
#using (Html.BeginForm("SendMail", "Contract", null, FormMethod.Post), new { id = "myForm" })
{
<input type="hidden" value=#Html.ViewData.Model.StudentId name="studentId" />
<input type="hidden" value=#Html.ViewData.Model.CompanyId name="companyId" />
<input type="hidden" value=#Html.ViewData.Model.ApplicationId name="applicationId" />
<input type="text" name="companyCVR" />
}
<input type="button" value="Submit" onclick="$('#myForm').submit();" />

Wrong hidden filed value is being passed to the Action Method

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.

Ajax.BeginForm is loading a new page even with UpdateTargetId

I did this right here:
#using (Ajax.BeginForm("UserProjMetric", "Users", new AjaxOptions { UpdateTargetId = "dailyMetric" }))
{
<input type="hidden" id="id" name="id" value="#Model.Id"/>
<span class=""><input type="text" class="startDate dates" placeholder="Start Date" id="startDate" name="startDate"></span>
<span class=""><input type="text" class="endDate dates" placeholder="End Date" id="endDate" name="endDate"></span>
<input class="btn btn-small" type="submit" value="Submit" />
}
But instead of updating the target id it just takes the entire partial and loads it on a new page. I really just want the specific div on the page updated not the entire page.
I am returning a partial view:
return PartialView("_UserProjMetric", model);

Html.BeginRouteForm accept-charset attribute

I'm building a form in Razor like below:
#using (Html.BeginRouteForm("foo", new { controller = "foo", action = "bar" }, FormMethod.Post, new { id="foo", enctype="multipart/form-data", accept-charset="utf-8" }))
{
<label for="file">File</label>
<input type="file" name="file" id="file" />
<input type="submit" value="Send"/>
}
I need to get some attributes in the form tag. But the compiler doesn't like the dash in accept-charset. How might I allow an object property in C# have a dash?
Use an underscore in the property name: accept_charset
MVC automatically convert underscores in html attribute properties to dashes:
#using (Html.BeginRouteForm("foo", new { controller = "foo", action = "bar" }, FormMethod.Post, new { id="foo", enctype="multipart/form-data", accept_charset="utf-8" }))
{
<label for="file">File</label>
<input type="file" name="file" id="file" />
<input type="submit" value="Send"/>
}
Credit: How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

Categories