Reputation: 283
Just sending a int Data from View To Controller Action. but the controller action is not receiving that int data/ cannot map that int data.
my controller =>
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ConfirmNewBatchRequest(int? id)
{
if ((id?? 0) == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Studentassignbatche ConfirmStudentassignbatche = db.Studentassignbatches.Find(id);
Batche FindBatche = db.Batches.Find(ConfirmStudentassignbatche.batch_code);
if (ConfirmStudentassignbatche == null)
{
return HttpNotFound();
}
ConfirmStudentassignbatche.StatusCode = 1;
db.Financeofstudents.Add(new Financeofstudent()
{
UserId = ConfirmStudentassignbatche.UserId,
batch_code = ConfirmStudentassignbatche.batch_code,
debit = FindBatche.amount,
credit = 0,
balance = FindBatche.amount,
lastTrunsaction = DateTime.Now,
entry_date = DateTime.Now
});
TryUpdateModel(ConfirmStudentassignbatche, new string[] { "StatusCode" });
db.SaveChanges();
TempData["BatchConfirmSuccess"] = "Success";
return RedirectToAction("Index");
}
and my view =>
@using Something
@model IEnumerable<Studentassignbatche>
@{
ViewBag.Title = "Confirm New Batch Request From Student";
IEnumerable<Course> CoursesTable = TempData["Courses"] as IEnumerable<Course>;
IEnumerable<UserDetail> UserDetailTable = TempData["UserDetails"] as IEnumerable<UserDetail>;
}
@section PageDescription{
<section class="content-header">
<h1>
@ViewBag.Title
<small>Tsms-admin</small>
</h1>
</section>
}
<div class="table-responsive">
<table class="table table-striped table-inverse table-bordered">
<tr>
<th>#</th>
<th>
@Html.DisplayNameFor(model => model.UserId)
</th>
<th>
@Html.Label("Student Name")
</th>
<th>
@Html.DisplayNameFor(model => model.batch_code)
</th>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th>
@Html.Label("Vendor Name")
</th>
<th>
@Html.DisplayNameFor(model => model.adding_date)
</th>
<th></th>
</tr>
@{
int counter = 1;
}
@foreach (var item in Model)
{
<tr>
<td>
@counter
</td>
<td>
@Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
@{
var UserDetailsId = UserDetailTable.Where(x => x.UserId == item.UserId).Select(x => x.id).FirstOrDefault();
var name = UserDetailTable.Where(x => x.UserId == item.UserId).Select(x => x.fullname).FirstOrDefault();
}
@Html.ActionLink(name, "Details", "Students", new { id = UserDetailsId }, null)
</td>
<td>
@Html.ActionLink(item.batch_code, "Details", "Batche", new { id = item.batch_code }, null)
</td>
<td>
@Html.ActionLink(item.name, "Details", "Course", new { id = item.name }, null)
</td>
<td>
@{
var vendorname = CoursesTable.Where(x => x.name == item.name).Select(x => x.vendor_heading).FirstOrDefault();
}
<label style="font-weight:normal !important">@vendorname</label>
</td>
<td>
@Html.DisplayFor(modelItem => item.adding_date)
</td>
<td style="width:100px;">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(modelitem => item.id)
<div class="form-actions no-color">
<input type="submit" value="Confirm" class="btn btn-success" />
</div>
}
</td>
</tr>
counter++;
}
</table>
</div>
The rendered form inside the loop looks like this:
<form action="/Admin/ConfirmNewBatchRequest" method="post">
<input name="__RequestVerificationToken" type="hidden" value="K4GmhPUCkcqqclPtxW7F1YpiT_6mQBBZu7Wi8JtfQDMWdmCPMQsbjBfmtr9t8pSBrOV6Yixhhtz0B-OfMtxj4Y8dOwrdRBXlz9v0sD7O8YE1" />
<input data-val="true" data-val-number="The field id must be a number." data-val-required="The id field is required." id="item_id" name="item.id" type="hidden" value="3" />
<div class="form-actions no-color">
<input type="submit" value="Confirm" class="btn btn-success" />
</div>
</form>
and here is how my model binds with the view =>
public class Studentassignbatche
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
/// <summary>
/// ////////
/// </summary>
[Required(AllowEmptyStrings = false, ErrorMessage = "User Id Is Required!")]
[MaxLength(12, ErrorMessage = "The Max length Of User ID is 12 Character!")]
[RegularExpression("[1-3]{2}-[0-9]{5}-[123]{1}|[1-3]{2}-[0-9]{7}-[123]{1}", ErrorMessage = "Invalid Id,It should [xx]-[xxxxx]-[x] or [xx]-[xxxxxxx]-[x]!")]
[Display(Name = "User ID")]
public string UserId { get; set; }
/// <summary>
/// /////////
/// </summary>
[Required(AllowEmptyStrings = false, ErrorMessage = "Course Name Is Required!")]
[MaxLength(700, ErrorMessage = "The Max Length For Course Name Is 700 Character!")]
[Display(Name = "Course Name")]
public string name { get; set; }
/// <summary>
/// /////////
/// </summary>
[Required(AllowEmptyStrings = false, ErrorMessage = "Batch Code Is Required!")]
[MaxLength(700, ErrorMessage = "The Max Length For Batch Code Is 700 Character!")]
[Display(Name = "Batch Code")]
public string batch_code { get; set; }
/// <summary>
/// ///////
/// </summary>
[Required(AllowEmptyStrings = false, ErrorMessage = "Status Is Required!")]
[RegularExpression("^(?:complete|Complete|in progress|In progress)$", ErrorMessage = "Invalid Status!")]
[Display(Name = "Current Status")]
public string status { get; set; }
/// <summary>
/// ////////
/// </summary>
[Display(Name = "Course Completion Date")]
[DataType(DataType.DateTime,ErrorMessage="Invalid Date!")]
public Nullable<DateTime> completion_date { get; set; }
[Display(Name="Date Of Addition")]
[DataType(DataType.DateTime,ErrorMessage="Invalid Date!")]
public DateTime adding_date { get; set; }
/// <summary>
/// /////////
/// </summary>
[RegularExpression("^[01]{1}$", ErrorMessage = "Invalid Status Code!")]
[Required(ErrorMessage="Status Code Is Required!")]
public int StatusCode { get; set; }
//relationship with anothere table------
[ForeignKey("UserId")]
public User User { get; set; }
/// <summary>
/// //////
/// </summary>
[ForeignKey("name")]
public Course Course { get; set; }
/// <summary>
/// ///////
/// </summary>
[ForeignKey("batch_code")]
public Batche Batche { get; set; }
}
and on controller when I debug I found out that =>
and i try using =>
public ActionResult ConfirmNewBatchRequest(Studentassignbatche Studentassignbatche)
{
if (Studentassignbatche == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
but on debut it is still showing me a null object .
why this is happening because in view side it can generate more than one <form></form>
. but as far as I can understand if the view generate more than one <form></form>
still every form will get one hidden input field.
and when the form will submit it will that particular hidden field which is associated with that <form>
. Or One thing my URL look like http://localhost:43847/Admin/ConfirmNewBatchRequest
is there any problem with URL ? Then why this problem is arising, and How to get rid of that problem.
Upvotes: 0
Views: 1110
Reputation: 61904
The problem is that your form and your postback method don't match.
In your form, the rendered hidden field's name
is item.id
. However, your action method expects simply a single int called id
. The form will submit it as if id
is part of an object called item
.
The HTML helper you've used to render the field is designed for when you want to post back the whole model, not just one field - i.e. in that case your action method would have to accept an object of type Studentassignbatche
.
To fix this, you can use the simpler version of the HiddenField helper:
@Html.Hidden("id", item.id)
This should render something like:
<input name="id" type="hidden" value="3" />
which will mean that the name
matches the name expected by your action method.
Upvotes: 2