How to pass selected date as input in MVC4? - asp.net-mvc-4

when i used the below code, i am getting null reference not set to an instance of an object in mvc4. I used FormCollection method to pass date as input. It shows me null value for sd (sd is startdate variable) while i traced out. How to resolve this exception?
Controller:
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
List<tblGroup> allg = new List<tblGroup>();
using (portalconnectionstring con = new portalconnectionstring())
{
allg = con.grt.OrderBy(m => m.groupname).ToList();
}
ViewBag.disg = new SelectList(allg, "groupid", "groupname");
var sd = formCollection["txtDate"]; //Showing null value here while i traced out
var ed = formCollection["Txtenddate"];
....
.....
}
View:
#using (Html.BeginForm("Index","MyController",FormMethod.Post,new {id="form1"}))
{
<div>
#Html.Label(" ",new { id ="Label1" })
<input id="txtDate" type="text" value="Startdate: "/>
<div>
<input id="Txtenddate" type="text" value="Enddate: "/>
</div>
<div>
#Html.Label("Group Name", new{id="lblGroupName"})
</div>
<div>
#Html.DropDownListFor(model => model.groupid, #ViewBag.disg as SelectList, "select")
#Html.ValidationMessageFor(model=>model.groupid)
</div>
<input type="submit" id="Button1" Value="Submit"/>
</div>
}

You need to give your inputs a name attribute
<input id="txtDate" name="txtDate" type="text" value="Startdate: "/>
However this will be done automatically if you use the html helpers to bind to your model properties, for example #Html.TextBoxFor(m => m.txtDate), in which case you can bind back to you model in the POSt method rather than using FormCollection

Related

NET Core - Ajax post not binding child model

Child model binding is not working properly on Ajax post call in .Net core controller method
I am using below model -
public class UserViewModel
{
public UserViewModel()
{
UserAttribute = new CAMPv2.Models.AutoPoco.UserAttribute();
}
public UserAttribute UserAttribute { get; set; }
}
public class UserAttribute
{
[JsonPropertyName("FirstName")]
public string FirstName { get; set; }
}
Below is the Ajax call -
#using User.Models
#model UserViewModel
#{
ViewData["Title"] = "UserDetails";
}
<form class="kt-form" id="kt_form">
<div class="kt-wizard-v3__content" data-ktwizard-type="step-content" data-ktwizard-state="current">
<div class="kt-form__section kt-form__section--first">
<div class="form-group row required">
<label for="FirstName" class="col-md-3 col-form-label k-font-bold text-md-right control-label">First Name</label>
<div class="col-6">
<input type="text" class="form-control" name="FirstName" placeholder="" required asp-for="UserAttribute.FirstName">
</div>
</div>
</div>
<div class="btn btn-brand btn-md btn-tall btn-wide btn-bold btn-upper" data-ktwizard-type="action-submit" id="btnSubmit">Submit</div>
</div>
</form>
<script>
$("#btnSubmit").click(function () {
var formData = $("#kt_form").serialize();
alert(formData);
$.ajax({
url: "/User/CreateUser/",
data: formData,
type: "POST",
dataType: "json",
success: function (result) {
if (result.success) {
alert('data submitted successfully');
}
},
error: function (result) {
alert('failed to submit data');
},
});
});
</script>
Below is action method -
[HttpPost]
public ActionResult CreateUser(UserViewModel model)
{
try
{
return Json(new { success = true, result = model, errorMessage = "" });
}
catch (WebException ex)
{
return Json(new { success = false, errorMessage = ex.Message });
}
}
Model values are null. Can anyone please let me know what i am missing here? Ajax post call is returning model to action method with null values.
Model values are null. Can anyone please let me know what i am missing here? Ajax post call is returning model to action method with null values.
As far as I know, if you use $("#kt_form").serialize() it will serialize the form into from data according to input tag's name attribute.
But you have set the input tag's name to FirstName. That means the asp.net core model binding will bind the value to FirstName property. But the value is used for UserAttribute's FirstName not the viewmodel's FirstName. This is the reason why your model binding result is null.
To solve this issue, I suggest you could try to use asp.net core tag helper to help you generate the input tag name or you could modify the name property to UserAttribute.FirstName.
You could modify the input as below:
<input type="text" class="form-control" placeholder="" required asp-for="#Model.UserAttribute.FirstName">
Detail view codes:
<form class="kt-form" id="kt_form">
<div class="kt-wizard-v3__content" data-ktwizard-type="step-content" data-ktwizard-state="current">
<div class="kt-form__section kt-form__section--first">
<div class="form-group row required">
<label for="FirstName" class="col-md-3 col-form-label k-font-bold text-md-right control-label">First Name</label>
<div class="col-6">
<input type="text" class="form-control" placeholder="" required asp-for="#Model.UserAttribute.FirstName">
</div>
</div>
</div>
<div class="btn btn-brand btn-md btn-tall btn-wide btn-bold btn-upper" data-ktwizard-type="action-submit" id="btnSubmit">Submit</div>
</div>
</form>
Result:

Checkbox list values empty when ModelState is not valid and ASP.NET Core does return Page()

I created an ASP.NET Core 3.1 project. I have a form in it with several checkbox lists. I can get the values into the properties in POST and they are correctly filled in (e.g. List SelectedItems). However for some custom fields I have to do a validation in OnPost() method and if the conditions are not met or a ModelState is not valid, it return Page(). Normally I would expect that every property that was filled in in the form is still filled in, but the checkboxes are always empty and not a single one is checked. The other data (radio buttons, textboxes, etc.) are still filled in.
I even tried to put the values within the Razor page, but even then neither of the checkboxes was checked.
Here is an example of one of the checkboxes:
In Razor page:
#for (var i = 1; i <= 10; i++){
<input name="AreChecked" type="checkbox" id="#i" value="#i" /> #i<br />
<input type="hidden" value="true" id="#i" name="AreChecked" />}
Behind code:
[BindProperties]
public class TestFormModel : PageModel
{
[BindProperty]
public List<int> AreChecked { get; set; }}
public IActionResult OnPost()
{
//some other form check statements here
//...
if (ModelState.IsValid)
{
//process data code...
}
return Page();
}
Can someone help me with this?
You could use JQuery to achieve as shown :
#page
#model RazorPages3_1.AddimgModelModel
<div class="row">
<div class="col-md-4">
<form enctype="multipart/form-data" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Petimg.PetName" class="control-label"></label>
<input asp-for="Petimg.PetName" class="form-control" />
<span asp-validation-for="Petimg.PetName" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="Uploads" class="form-control" />
</div>
#for (var i = 1; i <= 10; i++)
{
<input name="AreChecked" type="checkbox" id="#i" value="#i" /> #i<br />
<input type="hidden" value="true" id="#i" name=""AreChecked" />
}
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
<script>
var checkedlist = #Html.Raw(Json.Serialize(Model.AreChecked));;
if (checkedlist.length > 0) {
$.each(checkedlist, function (index, value) {
$('input[type=checkbox]').each(function () {
var id = $(this).attr("id");
if (id == value) {
$(this).attr('checked', 'checked');
}
})
});
}
</script>
}
Result

what is the use of insert mode on AJAXFORM in MVC?

When i am clicking the ajax from is loaded the partila view correctly inside the div have id as mytraget. But my question is what is the use of insertmode in ajax form.
On submitting the ajax form it always load the partial view inside of the div have id as mytraget on all type of insert mode. Then what is the of insert mode?
My original view named as MyView
#model Example.Models.mytest
<div id="mytraget"> </div>
#using(Ajax.BeginForm("myParialAjax", new AjaxOptions() { InsertionMode = InsertionMode.InsertBefore, UpdateTargetId = "mytraget" }))
{
<p>Name</p> #Html.TextBoxFor(m => m.string1)
<input type="submit" value="Submit" />
}
My Cobtroller Method
[HttpPost]
public PartialViewResult myParialAjax(mytest s)
{
return PartialView("Mypartial", s);
}
My Parial view which is named as Mypartial
#model Example.Models.mytest
<p>
#Html.TextBoxFor(m =>m.string1)
</p>
In all type of insert mode i get partial view inside of the the below div.
Output :
<div id="mytraget">
<p>
<input id="string1" type="text" value="asdf" name="string1">
</p>
</div>
I got myself the answer What i am missing is Need to insert some tags inside of the target tag.
Like below:
#model Example.Models.mytest
<div id="mytarget">
<p> my para </p>
</div>
#using(Ajax.BeginForm("myParialAjax", new AjaxOptions() { InsertionMode = InsertionMode.InsertBefore, UpdateTargetId = "mytarget" }))
{
<p>Name</p> #Html.TextBoxFor(m => m.string1)
<input type="submit" value="Submit" />
}
Now here InsertionMode.InsertBefore will insert my partial view above the paragraph tag and InsertionMode.InsertAfter will insert my partial view after the paragraph tag and InsertionMode.Replace will replace the whole things which is inside of the tag with my target id.

choosing between 2 actions in one controller with single view by checkbox

I got 2 actions in my controller, I want to choose which action to execute by checkbox in my razor view.
here is my controller:
public ActionResult Person(string searchString)
{
var person = from p in db.Persons
select p;
if (!String.IsNullOrEmpty(searchString))
{
person = person.Where(oo => oo.Name.ToUpper() == searchString);
}
return View(person);
}
public ActionResult Job(string jobString)
{
var jobs = from j in db.Jobs
select j;
if (!String.IsNullOrEmpty(jobString))
{
jobs = jobs.Where(oo => oo.Name.ToUpper() == jobString);
}
return View(jobs);
}
when I check a case I would like to execute the query search for this specific case
here is my view:
<div>
<form method="POST">
<div>
<input type="checkbox" name="Person" value="Person" style="margin-left: 54px"/>Person
</div>
<div class="Job">
<input type="checkbox" name="Job" value="Job" />Job
</div>
#using (Html.BeginForm())
{
<p>
<input type="text" name="SearchString" style="margin-left: 90px;" />
<input type="submit" value="Search" />
</p>
}
</form>
Post to a single action method, then call one of your existing methods depending on the value of the checkbox.
public ActionResult Search(bool isJobSearch, string searchString)
{
if (isJobSearch)
{
return Job(searchString);
}
else
{
return Person(searchString);
}
}
private ActionResult Person(string searchString)
{
// As your example
}
private ActionResult Job(string jobString)
{
// As your example
}
I am just correcting your html
Your html contains two form tags. I am not sure about the usage of form with in form tags. html.beginform will create internally another form tag when gets executed.So better one form tag will contain all elements to make a post.
#using (Html.BeginForm("Search","Home"))
{
<div>
<input type="checkbox" name="Person" value="Person" style="margin-left: 54px"/>Person
</div>
<div class="Job">
<input type="checkbox" name="Job" value="Job" />Job
</div>
<p>
<input type="text" name="SearchString" style="margin-left: 90px;" />
<input type="submit" value="Search" />
</p>
}
}
in controller
public ActionResult Search(FormCollection form)
{
//do some condition based on your needs
if(form["SearchString"]=="Job")
return RedirectToAction("Job");
else
return RedirectToAction("Person");
}
public ActionResult Person()
{
}
public ActionResult Job()
{
}

How do I pass the value to Controller from View without Creating any Object for Model in View in ASP.NET MVC4?

I am new to ASP.NET MVC4 With Entity Framework. I just want to pass the value from View to Controller, I am unable to get it. Please help me to get it. Thanks in advance.
This is my View code:
<form id="changepassword" method="post" action="#Url.Action("Change", "ChangePassword")">
<input type="password" value="currentpswd" class="form-control pword" placeholder="Current Password" />
<input type="password" value="newpswd" class="form-control pword" placeholder="New Password" />
<input type="password" value="cnfrmpswd" class="form-control pword" placeholder="Confirm Password" />
<button class="btn btn-success btn-block" value="change">Submit</button>
</form>
This is my Controller code:
[HttpPost]
public ActionResult Change(FormCollection forms)
{
if (ModelState.IsValid)
{
string currentpswd=Convert.ToString(forms["currentpswd"]);
string newpass= (string)forms["newpswd"];
string confirmpass=forms["cnfrmpswd"];
Tbl_Users user = new Tbl_Users();
if (newpass == confirmpass)
{
user.UserPassword = newpass;
db.SaveChanges();
}
else
{
}
}
return RedirectToAction("Index", "ChangePassword");
}
How about using form collection You would create an action method that will handle the post when the user clicks the post button:
It will post a collect of the form fields to the controller, you can then reference by using the Name property from the original form fields.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection forms)
{
var userPassword = (string)forms["UserPassword"];
var userSalt = (string)forms["UserSalt"];
}