The Model Passed to Dictionary is of one type whereas the Dictionary Requires Model Item of Type ViewModels - asp.net-mvc

I am working with the partial views to attain a functionality in which I have to delete data from two tables having a one to many relationship in database. For this, I am using same “Delete” function in controller for both tables. I have added two models for these tables in the Delete view using ViewModels and have rendered both partial views in the main Delete Page to display relevant data on each delete view but after doing all this coding I am getting the following error.
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.tblPatientBill_804486DE0CB5E4B1C416CFC35E7B001C20B1FDB3674F40F1811012FFC9BAA908', but this dictionary requires a model item of type 'HMS.ViewModels.DeleteViewModel'.
Here is my Code Details:
PatientsBillController:
public ActionResult Delete(int? id,DeleteViewModel model)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PatientsBillViewModel billmodell = new PatientsBillViewModel();
PatientsBillDetailViewModel billdetailmodell = new PatientsBillDetailViewModel();
tblPatientBill bill = db.tblPatientBills.Find(id);
tblPatientBillDetail billdetail = db.tblPatientBillDetails.Find(id);
if (billdetail == null)
{
if (bill == null)
{
return HttpNotFound();
}
else
{
billmodell.ID = bill.ID;
billmodell.PatientAppointmentID = bill.PatientAppointmentID;
billmodell.BillNo = bill.BillNo;
billmodell.Amount = bill.Amount;
billmodell.Discount = bill.Discount;
billmodell.CreatedAt = bill.CreatedAt;
billmodell.CreatedBy = bill.CreatedBy;
billmodell.Description = bill.Description;
return View(billmodell);
}
}
else
{
billdetailmodell.ID = billdetail.ID;
billdetailmodell.PatientBillID = billdetail.PatientBillID;
billdetailmodell.Amount = billdetail.Amount;
billdetailmodell.CreatedAt = billdetail.CreatedAt;
billdetailmodell.CreatedBy = billdetail.CreatedBy;
billdetailmodell.Description = billdetail.Description;
return View(billdetail);
}
}
Delete.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "Delete";
Layout = null;
}
#{Html.RenderPartial("PatientsBillDelete", Model); }
#{Html.RenderPartial("PatientsBillDetail", Model); }
ViewModel.cs:
public class DeleteViewModel
{
public PatientsBillViewModel billmodel { set; get; }
public PatientsBillDetailViewModel billdetailmodel { set; get; }
}
public class PatientsBillViewModel
{
public int ID { get; set; }
public int PatientAppointmentID { get; set; }
public string BillNo { get; set; }
public float Amount { get; set; }
public float Discount { get; set; }
public string CreatedAt { get; set; }
public string CreatedBy { get; set; }
public string Description { get; set; }
}
public class PatientsBillDetailViewModel
{
public int ID { get; set; }
public int PatientBillID { get; set; }
public float Amount { get; set; }
public string CreatedAt { get; set; }
public string CreatedBy { get; set; }
public string Description { get; set; }
}
PartialViews are:
PatientBillDelete.cshtml
PatientBillDetail.cshtml
PatientBillDelete.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "PatientsBill Delete";
}
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Delete</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<h3>Are You Sure You Want To Delete This?</h3>
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.ID)
<br />
#Html.DisplayFor(m => m.billmodel.ID)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.PatientAppointmentID)
<br />
#Html.DisplayFor(m => m.billmodel.PatientAppointmentID)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.BillNo)
<br />
#Html.DisplayFor(m => m.billmodel.BillNo)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Amount)
<br />
#Html.DisplayFor(m => m.billmodel.Amount)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Discount)
<br />
#Html.DisplayFor(m => m.billmodel.Discount)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.CreatedAt)
<br />
#Html.DisplayFor(m => m.billmodel.CreatedAt)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.CreatedBy)
<br />
#Html.DisplayFor(m => m.billmodel.CreatedBy)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Description)
<br />
#Html.DisplayFor(m => m.billmodel.Description)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions no-color">
#Html.HiddenFor(m => m.billmodel.ID)
<input type="submit" value="Delete" class="btn btn-default" /> |
#Html.ActionLink("Back to List", "EditBill")
</div>
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
PatientsBillDetail.cshtml
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "PatientsBill Delete";
}
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Delete</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<h3>Are You Sure You Want To Delete This?</h3>
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.ID)
<br />
#Html.DisplayFor(model => model.billdetailmodel.ID)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.PatientBillID)
<br />
#Html.DisplayFor(model => model.billdetailmodel.PatientBillID)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.Amount)
<br />
#Html.DisplayFor(model => model.billdetailmodel.Amount)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.CreatedAt)
<br />
#Html.DisplayFor(model => model.billdetailmodel.CreatedAt)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.CreatedBy)
<br />
#Html.DisplayFor(model => model.billdetailmodel.CreatedBy)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.Description)
<br />
#Html.DisplayFor(model => model.billdetailmodel.Description)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions no-color">
#Html.HiddenFor(model => model.billdetailmodel.ID)
<input type="submit" value="Delete" class="btn btn-default" /> |
#Html.ActionLink("Back to List", "EditBill")
</div>
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
I think there is problem with my controller logic how can I look for different ids passed in the Delete function and check in two different table and pass result to viewmodel?
Please tell me what I am doing wrong in it. Thanks in advance

You are actually returning returning wrong object to your View. You should be passing the DeleteViewModel object back to your View something like :
DeleteViewModel deleteViewModel = new DeleteViewModel ();
deleteViewModel.billmodell = billmodell;
deleteViewModel.billdetailmodel = billdetailmodell;
and then pass it in your View() method call:
return View(deleteViewModel);
Your code after loading records from db should be like:
DeleteViewModel deleteViewModel = new DeleteViewModel();
deleteViewModel.billmodell = new PatientsBillViewModel(); ;
deleteViewModel.billdetailmodel = new PatientsBillDetailViewModel();
tblPatientBill bill = db.tblPatientBills.Find(id);
tblPatientBillDetail billdetail = db.tblPatientBillDetails.Find(id);
if (bill != null)
{
deleteViewModel.billmodell.ID = bill.ID;
deleteViewModel.billmodell.PatientAppointmentID = bill.PatientAppointmentID;
deleteViewModel.billmodell.BillNo = bill.BillNo;
deleteViewModel.billmodell.Amount = bill.Amount;
deleteViewModel.billmodell.Discount = bill.Discount;
deleteViewModel.billmodell.CreatedAt = bill.CreatedAt;
deleteViewModel.billmodell.CreatedBy = bill.CreatedBy;
deleteViewModel.billmodell.Description = bill.Description;
}
if(billdetail != null)
{
deleteViewModel.billdetailmodel.ID = billdetail.ID;
deleteViewModel.billdetailmodel.PatientBillID = billdetail.PatientBillID;
deleteViewModel.billdetailmodel.Amount = billdetail.Amount;
deleteViewModel.billdetailmodel.CreatedAt = billdetail.CreatedAt;
deleteViewModel.billdetailmodel.CreatedBy = billdetail.CreatedBy;
deleteViewModel.billdetailmodel.Description = billdetail.Description;
}
return View(deleteViewModel);

Related

Calling a view from different models in ASP.NET MVC

In my ASP.NET MVC application in the view, I'm calling another view that is not related to the current model. There I need some help that how to call the different model views from another view.
#model Asp_PASMVC.Models.VehicleService
#using Asp_PASMVC.Infrastructure
#{
ViewBag.Title = "View";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> CompanyList = (List<SelectListItem>)TempData.Peek("ComapnyList");
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
List<SelectListItem> Employees = (List<SelectListItem>)TempData.Peek("EmployeeList");
List<SelectListItem> Location = (List<SelectListItem>)TempData.Peek("LocationList");
Asp_PASMVC.Models.AppRequest RequestDetails = (Asp_PASMVC.Models.AppRequest)TempData.Peek("RequestDetails");
}
#{
Html.RenderPartial("_MainRequestView", RequestDetails);
}
#using (Html.BeginForm("WorkshopUpdate", "VehicleService", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.Req_Id)
#Html.AntiForgeryToken()
if (Model != null && Model.VehicleServiceApproveDetails != null)
{
foreach (Asp_PASMVC.Models.VehicleServiceApproveDetails Emp in Model.VehicleServiceApproveDetails)
{
Html.RenderPartial("_WorkshopUpdate", Emp);
}
}
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header">
<h3 class="card-title">Approver Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<div class="card-body">
<div>
<fieldset id="pnlApproverList" style="display:none">
<legend><h5>To whom you want to send this request for approval ? </h5> </legend>
<br />
<ul id="RequApprover" style="list-style-type: none">
#if (Model != null && Model.ApprovalPartyList != null)
{
foreach (Asp_PASMVC.Models.ApprovalParty Emp in Model.ApprovalPartyList)
{
Html.RenderPartial("_ApprovalView", Emp);
}
}
</ul>
<button type="button" id="addAnotherApprover" class="btn btn-success" href="#" onclick="this.style.display = 'none';">Add</button>
<script type="text/javascript">
$(function () {
// $("#movieEditor").sortable();
$("#addAnotherApprover").click(function () {
$.get('/VehicleService/AddApproverToReq', function (template) {
$("#RequApprover").append(template);
});
});
});
</script>
<br />
</fieldset>
</div>
</div>
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<div class="card-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update and Sent" class="btn btn-success" />
</div>
</div>
</div>
}
<p>
#Html.ActionLink("Back to List", "Index")
</p>
So likewise here the model is VehicleService. So within that view, I want to call another view that is not within the vehicleservice model.
But I cannot load that partial view within this view. Is there any way to do this?
#model Asp_PASMVC.Models.ApprovalParty
#using Asp_PASMVC.Infrastructure
#{
string UserLvel = TempData.Peek("UserLevelClaims").ToString();
}
<li style="padding-bottom:15px">
#using (Html.BeginCollectionItem("ApprovalPartyList"))
{
<div class="row">
<div class="col-md-5 col-sm-5">
<div class="form-group">
<label>
#Html.RadioButtonFor(m => m.Approve_Type, false)
<span class="radiomargin">For Manager</span>
</label>
<br />
#if (UserLvel != "1")
{
<label>
#Html.RadioButtonFor(m => m.Approve_Type, true)
<span class="radiomargin">For Top Manager </span>
</label>
#Html.ValidationMessageFor(model => model.Approve_Type, "", new { #class = "text-danger" })
}
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group row">
Select the Approver
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Approver_Id, new List<SelectListItem>(), new { #id = "ddlEmployees", #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Approver_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
}
</li>
Create a ViewModel which can have both Properties and pass that viewmodel to View
Model class:
public class VehicleSerivceViewModel
{
public VehicleService VehicleService { get; set; }
public ApprovalParty ApprovalParty { get; set; }
}
In View :
#model Asp_PASMVC.Models.VehicleServiceVewModel
pass ViewModel to partial as below:
#Model.ApprovalParty

Html.CheckBoxFor Returning Incorrect Value If Originally Unchecked

I have a ViewModel containing information for an object called ContactEvent. ContactEvent has a boolean called IsActive. I'm using #Html.CheckBoxFor() for a checkbox to let the user alter its value. The problem is that if the value is originally true and the user sets it to false, the model passed through the POST has the updated value. But if the value is originally false, the model passed through the POST always returns false still. I have no idea what is causing it.
View
#model ContactEventViewModel
#{
ViewBag.Title = "Contact Event";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<head>
<script src="~/datatables/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="~/datatables/css/jquery.dataTables.min.css" />
</head>
<body>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
#using (Html.BeginForm("ContactEvent", "ContactEvents", FormMethod.Post))
{
<h1>Edit Contact Event</h1>
#Html.HiddenFor(Model => Model.ContactEvent.ContactEventSysID, new { #Value = Model.ContactEvent.ContactEventSysID })
<div class="form-group row">
<label>Customer</label>
<div class="col-md-7 col-lg-7">
<Label>#String.Format("{1}, {0}", Model.Customer.FirstName, Model.Customer.LastName)</Label>
#Html.HiddenFor(Model => Model.Customer.CustomerSysID, new { #Value = Model.Customer.CustomerSysID })
</div>
</div>
<div class="form-group row">
<label>Date</label>
<div class="col-md-7 col-lg-7">
#Html.EditorFor(model => model.ContactEvent.Date, new { htmlAttributes = new { #class = "datepicker", #Name = "date", #PlaceHolder = "mm/dd/yyyy" } })
</div>
</div>
<div class="form-group row">
<label>Event Type</label>
<div class="col-md-7 col-lg-7">
#Html.DropDownListFor(Model => Model.ContactEvent.ContactEventTypeSysID, new SelectList(Model.ListOfContactEventTypes, "ContactEventTypeSysID", "Description"))
</div>
</div>
<div class="form-group row">
<label>Outcome</label>
<div class="col-md-7 col-lg-7">
#Html.DropDownListFor(Model => Model.ContactEvent.OutcomeSysID, new SelectList(Model.ListOfOutcomes, "OutcomeSysID", "Description"))
</div>
</div>
<div class="form-group row">
<label>Note</label>
<div class="col-md-7 col-lg-7">
#Html.TextBoxFor(Model => Model.ContactEvent.Note, new { #Value = Model.ContactEvent.Note })
</div>
</div>
<div class="form-group row">
<label>Created Date</label>
<div class="col-md-7 col-lg-7">
<label>#Model.ContactEvent.CreatedDate</label>
</div>
</div>
<div class="form-group row">
<label>Last Updated Date</label>
<div class="col-md-7 col-lg-7">
<label>#Model.ContactEvent.LastUpdatedDate</label>
</div>
</div>
<div class="form-group row">
<label>Active?</label>
<div class="col-md-7 col-lg-7">
#Html.CheckBoxFor(Model => Model.ContactEvent.IsActive, new { #Value = Model.ContactEvent.IsActive })
</div>
</div>
<input type="submit" id="updateButton" value="Submit" />
}
</div>
</body>
Method in Controller
[HttpPost]
public IActionResult ContactEvent(ContactEventViewModel contactEventViewModel)
{
if (ModelState.IsValid)
{
string connectionString = Startup.ConnectionString;
string query = "UPDATE [CRM].[dbo].[ContactEvent] " +
"SET [Date]=#Date, [ContactEventTypeSysID]=#ContactEventTypeSysID, [OutcomeSysID]=#OutcomeSysID, [Note]=#Note, [LastUpdatedDate]=#LastUpdatedDate, [IsActive]=#IsActive " +
"WHERE [ContactEventSysID]=#ContactEventSysID";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#Date", contactEventViewModel.ContactEvent.Date);
command.Parameters.AddWithValue("#ContactEventTypeSysID", contactEventViewModel.ContactEvent.ContactEventTypeSysID);
command.Parameters.AddWithValue("#OutcomeSysID", contactEventViewModel.ContactEvent.OutcomeSysID);
if (contactEventViewModel.ContactEvent.Note == null)
{
command.Parameters.AddWithValue("#Note", DBNull.Value);
}
else
{
command.Parameters.AddWithValue("#Note", contactEventViewModel.ContactEvent.Note);
}
command.Parameters.AddWithValue("#LastUpdatedDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
command.Parameters.AddWithValue("#IsActive", contactEventViewModel.ContactEvent.IsActive);
command.Parameters.AddWithValue("#ContactEventSysID", contactEventViewModel.ContactEvent.ContactEventSysID);
connection.Open();
command.ExecuteNonQuery();
}
}
}
return RedirectToAction("ContactEvent", "ContactEvents", new { ContactEventSysID = contactEventViewModel.ContactEvent.ContactEventSysID });
}
Let me know if you need any other code. Thanks in advance.
Please remove #Value = Model.ContactEvent.IsActive. This will let your model properly handle the value. Do not set any values unless you are sure, that you want to override model behavior.

Unable to pass RadioButton group selected value to Controller

I have a ViewModel defined as:
public class Fixtures
{
public int Id { get; set; }
public string HomeTeam { get; set; }
public string AwayTeam { get; set; }
public string HomeTeamCode { get; set; }
public string AwayTeamCode { get; set; }
public string League { get; set; }
public bool Home { get; set; }
public bool Draw { get; set; }
public bool Away { get; set; }
public string FixturePrediction { get; set; }
}
My view displays a list of these fixtures and for each fixture, I have a radio button grouping. I need some way of passing the selected radio button for each fixture to my Post method. My View and controller are as below:
View:
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
for (int i = 0; i < Model.Count(); i++)
{
#Html.HiddenFor(model => model[i].Id)
<div class="col-sm-6">
<div class="panel panel-primary panel-fixture">
<div class="panel-heading text-center fixturetitle">
#Html.DisplayFor(model => model[i].HomeTeam) v #Html.DisplayFor(model => model[i].AwayTeam)
#Html.HiddenFor(model => model[i].HomeTeam)
#Html.HiddenFor(model => model[i].AwayTeam)
</div>
<div class="panel-body">
<div class="container-fluid">
<div class="row">
<div class="col-xs-4 text-center">
<img src="~/Content/Images/#string.Concat(Model[i].HomeTeamCode, ".png")" class="fixturecrest" />
<div class="text-center">
#Html.DisplayFor(model => model[i].HomeTeamCode)
#Html.HiddenFor(model => model[i].HomeTeamCode)
</div>
</div>
<div class="col-xs-4 text-center">
<label class="text-center">
V <br />
</label>
</div>
<div class="col-xs-4 text-center">
<img src="~/Content/Images/#string.Concat(Model[i].AwayTeamCode, ".png")" class="fixturecrest" />
<div class="text-center">
#Html.DisplayFor(model => model[i].AwayTeamCode)
#Html.HiddenFor(model => model[i].AwayTeamCode)
</div>
</div>
</div>
<hr />
<div class="row">
<div class="text-center" role="group" aria-label="Fixture Prediction">
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
HOME
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Home, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
DRAW
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Draw, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
<div class="col-xs-4 text-center">
<button type="button" class="btn btn-xs btn-default">
AWAY
#Html.RadioButtonFor(model => model[i].FixturePrediction, Model[i].Away, new { #Name = Model[i].Id })
#Html.HiddenFor(model => model[i].FixturePrediction)
<span class="glyphicon glyphicon-check"></span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
<input type="submit" value="Confirm Predictions" class="btn btn-success" />
}
</div>
Post Method in Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Test(IEnumerable<Fixtures> test)
{
if (ModelState.IsValid)
{
}
return RedirectToAction("Test");
}
My field FixturePrediction is always null and I have attempted several variations of the 'radiobuttonfor' shown above.
All I need is to assign a value to FixturePrediction based on which radiobutton is selected. What am I missing?
Thanks in advance.
I think what you are trying to do is this, I am not sure why you are doing it the way you are doing it, but this is how you would implement Html.RadioButtonFor, it takes the model prop, and the value, you can add as many buttons as you want, and the selected radio value will be passed as the value for your model prop
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Home")
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Draw")
#Html.RadioButtonFor(model => model[i].FixturePrediction, "Away")
Another example

Cannot apply indexing with [] to an expression of type 'HttpRequest'

I am trying to get a value from a textbox of my View.
This is my View:
#model MyDataIndexViewModel
#{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email})
</div>
</div>
}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="btn btn-default pull-right" href="/ChangeMyData/Save">Speichern</a>
</div>
</div>
This is my Controller:
[HttpPost]
public ActionResult Save()
{
var email = Request["txtEmail"].ToString();
return View();
}
I get the error just as it says in the Title.
Thank you in advance!
VIEW:
#model MyDataIndexViewModel
#using (Html.BeginForm("Save", "CONTROLLER_NAME"))
{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email, id="txtEmail"})
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="submit btn btn-default pull-right">Speichern</a>
</div>
</div>
}
CONTROLLER
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
You can either use strongly-typed viewmodel binding:
View
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBox("txtEmail", Model.Email)
Controller
[HttpPost]
public ActionResult Save(MyDataIndexViewModel model)
{
var email = model.Email;
return View();
}
Or use a TextBoxFor directly for model binding:
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBoxFor(model => model.Email)
Or if you still want to use HttpRequest members, Request.Form collection (a NameValueCollection) is available to retrieve text from txtEmail input:
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
Note that Request["txtEmail"] is discouraged due to no compile time safety applied for it, because the key value may retrieved from Request.QueryString, Request.Form or other HttpRequestBase members.
Similar issue:
MVC TextBox with name specified not binding model on post
Access form data into controller using Request in ASP.NET MVC

is their anyway to return nothing in actionResult not to refresh that page if validations raised

this is my actionResult
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Payment(PaymentViewModel payment, string returnUrl)
{
PaymentModel paymentModel = new PaymentModel();
if (ModelState.IsValid)
{
CreditCardDetailsModel creditCardDetailsModel = new CreditCardDetailsModel();
creditCardDetailsModel.SecurityId = payment.SecurityId;
creditCardDetailsModel.ExpiryDate = payment.Month + payment.Year;
creditCardDetailsModel.CardNumber = payment.CardNumber;
paymentModel.CreditCardDetails = creditCardDetailsModel;
TempData["model"] = paymentModel;
return RedirectToAction("Payment");
}
var query = from state in ModelState.Values
from error in state.Errors
select error.ErrorMessage;
var errorList = query.ToList();
TempData["ErrorMessages"] = errorList;
ViewBag.MonthList = new SelectList(new[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" });
return new EmptyResult();
}
This is my partialView
#model Centra.Web.ViewModels.PaymentViewModel #using (Html.BeginForm("Payment", "Flight", FormMethod.Post,null))
{
#Html.AntiForgeryToken()
<div class="row space-form traveller-form">
<div class="col-lg-12">
<div class="col-lg-3 row">
<div class="fomr-group text-right">
<label>Credit Card No</label>
</div>
</div>
<div class="col-lg-8">
<div class="fomr-group col-lg-5 cardDetails">
#Html.TextBoxFor(p => p.CardNumber, new { #class = "form-control" })
</div>
<div ng-if="creditCardError == true" class="fomr-group col-lg-2 cardDetails">
<label>Please enter valid card number</label>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="col-lg-3 row">
<div class="fomr-group text-right">
<label>Expiry Date</label>
</div>
</div>
<div class="col-lg-8">
<div class="fomr-group col-lg-2 cardDetails ">
#Html.DropDownListFor(m=>m.Month, (SelectList)ViewBag.MonthList)
</div>
<div class="fomr-group col-lg-3 cardDetails row">
#Html.DropDownListFor(p => p.Year, Enumerable.Range(DateTime.Now.Year, 20)
.Select(x => new SelectListItem
{
Text = x.ToString(),
Value = x.ToString()
}
), new { #class = "form-control" })
</div>
</div>
</div>
<div class="col-lg-12">
<div class="col-lg-3 row">
<div class="fomr-group text-right">
<label>Name on card</label>
</div>
</div>
<div class="col-lg-8">
<div class="fomr-group col-lg-5 cardDetails">
#Html.TextBoxFor(p => p.NameOnCard, new { #class = "form-control" })
</div>
</div>
</div>
<div class="col-lg-12">
<div class="col-lg-3 row">
<div class="fomr-group text-right">
<label>CVV</label>
</div>
</div>
<div class="col-lg-8">
<div class="fomr-group col-lg-2 cardDetails">
#Html.TextBoxFor(p => p.SecurityId, new { #maxlength = "4", #class = "form-control", #placeholder = "CVV" })
</div>
<div class="fomr-group col-lg-5 cardDetails TotalPrice">
<label>The 3 digit number printed on the back of card</label>
</div>
</div>
</div>
<div class="col-lg-12 terms-conditions">
<div class="col-sm-11 col-lg-offset-1">
<div class="checkbox">
<label>
#* #Html.CheckBox("paymentCheckbox", new { #onclick = "function-to-open-dialog()" })*#
<input type="checkbox" id="paymentCheckbox" ng-model="paymentCheckbox">
I understand and agree to the rules and notifications of this fare, the booking privacy policy and the terms & conditions Centra Travels.
</label>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="col-lg-2 row">
<div class="fomr-group text-right">
</div>
</div>
<div class="col-lg-9 row">
<div class="fomr-group TotalPrice">
<label>
<h3>$ 36,613</h3>
<span>(Total inclusive all taxes)</span>
</label>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="col-lg-2 row">
<div class="fomr-group text-right">
</div>
</div>
<div class="col-lg-2 row">
<div class="fomr-group text-right col-lg-2">
#*<button type="submit" ng-disabled="!paymentCheckbox" ng-click="Payment(PaymentDetails)" class="btn btn-info makePaymentbtn">Make a Payment</button>*#
<button type="submit" ng-disabled="!paymentCheckbox" class="btn btn-info makePaymentbtn">Make a Payment</button>
</div>
#Html.Hidden("returnUrl", this.Request.RawUrl)
</div>
</div>
</div>
}
And other partialPages are not in mvcRazor formate their are in angular, so when i redirect to specific view(FlighBooking) //FlightBooking is my mainView in that multiple partial views are their, it is rending the FlightBooking View with but angular partialview are losing its states, so i tried by returning as return new EmptyResult(); but the page state is loosing, what should i do?
I want to bee on that same page without loosing its state if validations fails
If you don't want to refresh your page after go to action, you should use #Ajax.BeginForm instead #Html.BeginForm. There are a lot of tutorials on the internet.

Resources