This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I encountered a null exeception when i tried using this method and i dont know what is wrong.
Your help will be of great assistance thanks.
HttpPost
[HttpPost]
public ActionResult AddConsultation(Consultation _conmodel, int PatientId, int[] courses)
{
DataContext da = new DataContext();
if (courses != null)
{
foreach (var id in courses)
{
Symptoms course = da.Symptoms.Find(id);
_conmodel.Symptomses.Add(course);
}
}
da.Consultations.Add(_conmodel);
da.SaveChanges();
return View("Index");
}
I'm getting null exception on _conmodel.Symptomses.Add(course);
This is my view
<div class="form-group">
#Html.LabelFor(model => model.Symptomses, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.ListBox("courses")
#Html.ValidationMessageFor(model => model.Symptomses, "", new {#class = "text-danger"})
</div>
<br/>
<br/>
<hr/>
</div>
<div class="form-group">
<br/>
<hr/>
#Html.LabelFor(m => m.illness, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextAreaFor(m => m.illness, new {rows = "4", cols = "50", htmlAttributes = new {#class = "form-control"}})
</div>
</div>
</div>
<div class="col-md-6">
<h4 class="x"></h4>
<hr/>
<div class="form-group">
#Html.LabelFor(m => m.PresribedMed, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextAreaFor(m => m.PresribedMed, new {rows = "4", cols = "50", htmlAttributes = new {#class = "form-control"}})
</div>
<br/>
<br/>
<hr/>
</div>
<br/>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-primary" value="Add Consultation"/>
#*<button type="button" class="btn btn-primary" onclick="location.href='#Url.Action("Next", new { id = Model.UserName })';return false;"> Next</button>*#
</div>
</div>
</div>
}
</div>
<script type="text/javascript">
$("#courses").select2({
placeholder: "Please select symptoms",
maximumSelectionSize: 10,
width:300
});
</script>
_conmodel.Symptomses is probably null. Assuming Symptomses is a list, try this instead:
if (courses != null)
{
_conmodel.Symptomses = _conmodel.Symptomses ?? new List<Symptomses>();
foreach (var id in courses)
{
Symptoms course = da.Symptoms.Find(id);
_conmodel.Symptomses.Add(course);
}
}
This way, we can check if _conmodel.Symptomses is null, and if it is, instantiate it.
Related
I'm trying to submit my form using Ajax.beginform. I tried everything but i am getting this resource cannot found error.
I have two models - PatientEligibility and PatientDetails. Both contains 10-12 properties respectively.
I have created on viewmodel using those two models and I am trying to use some of the properties in one partial view and submitting that data button click
my view -
#model Portal.Models.EligibilityViewModel
<script type="text/javascript">
$(document).ready(function () {
$('input[type="checkbox"]').on('change', function () {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
});
</script>
<div class="row margin-top-0">
<div class="col-xs-12 col-sm-12">
<h4><b>Patient Eligibility</b></h4>
</div>
</div>
#using (Ajax.BeginForm("SubmitPatientEligibility", "Ophthalmic", new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
<div class="row margin-top-10">
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsAboveSixty, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbAbvSixty", #class = "form-control", Name = "group1[]" } })
The patient is 60 or over
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsBelowSixteen, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbUnderSixteen", #class = "form-control", Name = "group1[]" } })
The patient is under 16
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsBetweenForty, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbAbovenForty", #class = "form-control", Name = "group1[]" } })
The patient is 40 or over and is the parent/brother/sister/child of a person who has or has had gloucoma
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsStudent, new { #Name = "cbAgeEligibility", htmlAttributes = new { id = "cbStudent", #class = "form-control", Name = "group1[]" } })
The patient is full time student aged 16, 17 or 18 at the establishment below.
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<div class="checkbox">
<label>
#Html.CheckBoxFor(model => model.PatientEligibility.IsPrisoner, new { data_toggle = "collapse", data_target = "#dvseenNotseen", htmlAttributes = new { id = "cbPrisoner", #class = "form-control" } })
The patient is prisoner on leave from the prison detailed below
</label>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
#Html.LabelFor(p => p.PatientBenefit.NINNumber)
#Html.EditorFor(model => model.PatientBenefit.NINNumber, new { htmlAttributes = new { #class = "form-control", autocomplete = "off" } })
</div>
</div>
<div class="col-xs-12 col-sm-12">
<div class="margin-top-10">
<label>DATE OF BIRTH</label>
#Html.TextBoxFor(model => model.PatientBenefit.DOB, new { #class = "form-control", autocomplete = "off", #id = "datetimepicker1" })
</div>
</div>
<div class="row margin-top-10">
<div class="col-xs-12 col-sm-3">
<button class="btn btn-default" name="btnBack">Previous</button>
</div>
<div class="col-xs-12 col-sm-9 text-right">
<button class="btn btn-default" name="btnBack">Save Draft</button>
<button class="btn btn-success fa fa-chevron-right icon-right" name="btnNext" type="submit">Next</button>
</div>
</div>
}
and my model is like this -
public class EligibilityViewModel
{
public PatientEligibility PatientEligibility { get; set; }
public PatientBenefit PatientBenefit { get; set; }
}
I am trying to call this method on submit of Next button -
public class OphthalmicController : Controller
{
[HttpPost]
public ActionResult SubmitPatientEligibility(EligibilityViewModel model)
{
return null;
}
}
i dont know why but i am getting this 500 error resource cannot found for this method.
What am I missing here?
This question already has answers here:
How to get DropDownList SelectedValue in Controller in MVC
(9 answers)
Closed 5 years ago.
I am working on bulk sms in mvc. I have a view named SendSMS where i have fields like Sender ID, Numbers, Messagetext. Here, I am getting value of SenderID from Sender table where it consists Sender ID, Sender Name. Before sending message, user will add Sender Name from different view. As of now, I have added Sender Name. I am able to display Sender Name using dropdownList in SendSMS view.
After creating Sender ID and Sender Name, User enters SendSMS view to send Message. User will select Sender Name using dropdown list. He will add Numbers and Message text. When user clicks on Send button, the dropdown value is to passing to controller.
Here is the view code:
#using (Html.BeginForm("SendMessage", "SendSMS", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Compose New Message</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(Model => Model.SendSMSModel.SenderType, new { #class = "form-control-label" })
<div class="input-group">
<span class="input-group-addon input_email">
<i class="fa fa-user text-primary"></i>
</span>
#Html.EnumDropDownListFor(Model => Model.SendSMSModel.SenderType, new { #class = "form-control form-control-md" })
#Html.ValidationMessageFor(Model => Model.SendSMSModel.SenderType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(Model => Model.SendSMSModel.SenderId, new { #class = "form-control-label" })
<div class="input-group">
<span class="input-group-addon input_email">
<i class="fa fa-sort-numeric-asc text-primary"></i>
</span>
#Html.DropDownList("SenderId", new SelectList(ViewBag.SenderNameList, "SenderId", "SenderName"), "-Please Select-", new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.SendSMSModel.SenderId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(Model => Model.SendSMSModel.Numbers, new { #class = "form-control-label" })
<div class="input-group">
<span class="input-group-addon input_email">
<i class="fa fa-sort-numeric-asc text-primary"></i>
</span>
#Html.TextBoxFor(Model => Model.SendSMSModel.Numbers, new { #class = "form-control form-control-md" })
#Html.ValidationMessageFor(Model => Model.SendSMSModel.Numbers, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SendSMSModel.MessageText, new { #class = "form-control-label" })
<div class="input-group">
<span class="input-group-addon input_email">
<i class="fa fa-file-text text-primary"></i>
</span>
#Html.EditorFor(model => model.SendSMSModel.MessageText, new { htmlAttributes = new { #class = "form-control", #onkeyup = "javascript:ValidateCharactercount(this);", #rows = "10", #cols = "50" } })
#Html.ValidationMessageFor(model => model.SendSMSModel.MessageText, "", new { #class = "text-danger" })
</div>
<div id="divmessage" style="color: Red;">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send Now" class="btn btn-info" />
</div>
</div>
</div>
Controller:
`[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SendMessage(SMS_SignatureModel sms)
{
Inetlab.SMPP.SmppClient client = new Inetlab.SMPP.SmppClient();
client.Connect("***.**.***.**", ****);
if (client.Status == ConnectionStatus.Open)
{
client.SystemType = "****";
client.Bind("******", "******", ConnectionMode.Transmitter);
if (client.Status == ConnectionStatus.Bound)
{
IList<SubmitSmResp> respList = client.Submit(
SMS.ForSubmit()
.From(sms.SendSMSModel.SenderId)
.To(sms.SendSMSModel.Numbers)
.Text(sms.SendSMSModel.MessageText)
.DeliveryReceipt()
.Coding(DataCodings.Default)
);
if (respList.Count > 0 && respList[0].Status == CommandStatus.ESME_ROK)
{
Console.WriteLine("SMS has been sent");
foreach (SubmitSmResp resp in respList)
{
Console.WriteLine("MessageId: " + resp.MessageId);
}
}
client.UnBind();
}
client.Disconnect();
}
return RedirectToAction("SendMessage", "SendSMS");
}
`
Help would be appreciated.
#Html.DropDownListFor(model => model.SendSMSModel.SenderId, new SelectList(ViewBag.SenderNameList, "SenderId", "SenderName"), "-Please Select-", new { #class = "form-control" })
I have the following view:
#model GRCWebApp.ViewModels.NewClubInterestsViewModel
#{
ViewBag.Title = "Add Club Interests";
}
<div class="col-md-10 col-offset-md-1">
<h2 class ="text-success">Add Club Interests for #Html.DisplayFor(model => model.Name)</h2>
</div>
#using (Html.BeginForm("NewInterests", "Club", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="row">
<div class="col-md-8">
<div class="well bs-component">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(x => Model.ClubId)
<div class="form-group">
<div class="col-md-10 col-md-offset-1">
<h3>Tick the areas your club is interested/runs events in</h3>
</div>
</div>
<div class="col-md-offset-1">
#for (int i = 0; i < Model.ClubTypeInterests.Count(); i++)
{
<div>
#Html.HiddenFor(x => Model.ClubTypeInterests[i].InterestId)
#Html.CheckBoxFor(x => Model.ClubTypeInterests[i].selected)
#Html.LabelFor(x => Model.ClubTypeInterests[i].InterestName, Model.ClubTypeInterests[i].InterestName)
</div>
}
</div>
<div class="form-group">
<div class="row">
<div class="col-md-offset-1 col-md-12">
<input type="submit" name="Submit" value="Next" class="btn btn-success btn-lg" /> to setup Online membership
<input type="submit" name="Submit" value="Complete" class="btn btn-warning btn-sm" /> to just provide online event entries
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
#using (Html.BeginForm("AddInterest", "Club"))
{
#Html.AntiForgeryToken()
<hr />
<div class="row">
<div class="col-md-8">
<div class="well bs-component">
<div class="form-group">
<div class="col-md-12 col-md-offset-1">
<h3>Not listed? - Add extras here</h3>
</div>
</div>
#Html.HiddenFor(model => model.ClubTypeId)
#Html.HiddenFor(model => model.ClubId)
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-inline">
<div class="form-group">
<div class="row col-md-offset-1 col-md-11">
<div class="col-md-4">
#Html.LabelFor(model => model.InterestName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.InterestName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.InterestName, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
<input type="submit" value="Add" class="btn btn-info" style="margin-top: 22px" />
</div>
</div>
</div>
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Overtime the page loads the Validation message shows for InterestName in the second form AddInterest.
The Get method for the whole form is:
[HttpGet]
public ActionResult NewInterests(NewClubInterestsViewModel model, int id)
{
//Find the Club and then pass its id to the ViewModel
var club = db.Clubs.Find(id);
//model.ClubId = club.ClubId ;
//Interests List
IEnumerable<Interest> allExistingInterests;
//Generate a list of the interests that apply to that type of club
using (ApplicationDbContext context = new ApplicationDbContext())
{
allExistingInterests = context.Interests
.Where(s => s.ClubTypeId == club.ClubTypeId)
.OrderBy(s => s.InterestName)
.ToList();
}
IEnumerable<int> clubInterestIds = club.ClubInterests.Select(x => x.InterestId).ToList();
//Generate the ViewModel with the appropriate Interests
var viewModel = new NewClubInterestsViewModel
{
ClubId = club.ClubId,
Name = club.Name,
ClubTypeId = club.ClubTypeId,
ClubTypeInterests =
allExistingInterests.Select(
x => new ClubInterestsViewModel { InterestId = x.InterestId, InterestName = x.InterestName, selected = clubInterestIds.Contains(x.InterestId) }).ToArray()
};
return View(viewModel);
}
What do I need to do to stop the validation message showing on load?
Remove the NewClubInterestsViewModel model parameter from your GET method. It should be just
public ActionResult NewInterests(int id)
The first step in the model binding process is that instances of your parameters are initialized and then its properties are set based on form values, route values, query string values etc. In your case there are no values to set, so the properties of your model are their defaults, but because you have validation attributes on your properties, validation fails and errors are added to ModelState which are then displayed in the view.
I want to submit a single text field in a form. I have this view:
#model SenecaFormsServer.Areas.Dashboard.Models.EditProductModel
#using SenecaFormsServer.Areas.Dashboard.Models
#using Seneca.SfsLib.Connectors
<div id="ConnectorSettings-MAIL_PRODUCT_HANDLERS">
<h4>#Resources.Entity.Product.SettingsForConnector: Mail product handlers</h4>
#{
MailProductHandlersModel mailModel = Model.ConnectorModels["MAIL_PRODUCT_HANDLERS"] as MailProductHandlersModel;
}
<div class="form-group">
#Html.Label(Resources.Entity.Product.Sender, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Editor("MailProductHandlers_sender", new { htmlAttributes = new { #class = "form-control", #Value = mailModel.Sender, #placeholder = Model.CustomerConfig.DefaultSenderAddress } })
</div>
</div>
<div class="form-group">
#Html.Label(Resources.Entity.Product.MailSubject, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Editor("MailProductHandlers_subject", new { htmlAttributes = new { #class = "form-control", #Value = mailModel.Subject } })
</div>
</div>
<!--
<div class="form-group">
#Html.Label("Reply to form submitter", new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.CheckBox("MailProductHandlers_replytoFormSubmitter", new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
-->
<div class="form-group">
#Html.Label(Resources.Entity.Product.MailMessage, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.Message, new { htmlAttributes = new { #class = "form-control tiny-mce", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.Message)
#*#Html.TextArea("MailProductHandlers_message", mailModel.Message, new { #class = "form-control", #rows = 15 })*#
</div>
</div>
<div class="form-group">
#Html.Label(Resources.Entity.Product.GeneratePDF, new { #class = "text-bold control-label col-md-2" })
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.Label(Resources.Entity.Product.GeneratePDFYes) #Html.RadioButtonFor(model => model.IsChecked, true, new { #checked = "checked", #class = "pdfchecker" })
#Html.Label(Resources.Entity.Product.GeneratePDFNo) #Html.RadioButtonFor(model => model.IsChecked, false, new { #class = "pdfchecker" })
</div>
</div>
<div class="form-group">
<div id="hideLable">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
</div>
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
</div>
</div>
#using (Html.BeginForm("GeneratePDFFromHtml", "Product", FormMethod.Post)) {
#Html.AntiForgeryToken()
<div class="col-xs-12 padding-bottom-10">
#*<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF *#
<button type="submit" value="Save" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>
</div>
}
And I want to submit this part:
#using (Html.BeginForm("GeneratePDFFromHtml", "Product", FormMethod.Post)) {
#Html.AntiForgeryToken()
<div class="col-xs-12 padding-bottom-10">
#*<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF *#
<button type="submit" value="Save" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>
</div>
}
and this is the action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GeneratePDFFromHtml(EditProductModel model, string data, string designId)
{
string customerSchema = SfsHelpers.StateHelper.GetSchema();
//TemplateLibraryEntry entry = GetTemplateLibraryEntry(designId, customerSchema);
SubmittedForm sf = new SubmittedForm();
string schema = requestSchema;
customer_DbConnection db = new customer_DbConnection();
RenderFormController renderController = new RenderFormController();
renderController.GeneratePdf(data, db,sf);
//return RedirectToAction(model.DesignId, "Prdocut/Edit");
return Content("It works");
}
</div>
but the action method is not been triggered.
How to trigger the action method?
There has be created a PDF file from this textfield:
#using (Html.BeginForm("GeneratePDFFromHtml", "Product", null, FormMethod.Post, new { enctype = "multipart/form-data" })) {
#Html.AntiForgeryToken()
<div class="form-group">
<div id="hideLable">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
</div>
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
</div>
</div>
<div class="col-xs-12 padding-bottom-10">
<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF
#*<button type="submit" value="Save" class="btn btn-success"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>*#
</div>
}
and this is also the action method that has to been triggered and create the PDF file. But the method is not been triggered in the controller
The problem is that it is a partial view. So I solved like this:
Jquery:
$(document).ready(function () {
$('#btnGeneratePDF').click(function () {
var form = document.createElement("form");
form.setAttribute("GeneratePDFFromHtml", "post");
form.setAttribute("action", "GeneratePDFFromHtml");
form.setAttribute("target", "_blank");
var hiddenField = document.createElement("btnGeneratePDF");
//hiddenField.setAttribute("name", "search");
//hiddenField.setAttribute("value", "product1,product2");
hiddenField.setAttribute("type", "hidden");
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
});
});
and the view looks like now this:
<form method="post" id="form" name="form" action="#Url.Action("GeneratePDFFromHtml", "Product")" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<div id="hideLable">
#Html.Label(Resources.Entity.Product.PdfMessage, new { #class = "text-bold control-label col-md-2" })
</div>
<div class="col-lg-6 col-md-8 col-sm-10 ">
#Html.EditorFor(model => mailModel.PdfMessage, new { htmlAttributes = new { #class = "form-control tiny-mce", #id = "mceu_61", data_lang = System.Globalization.CultureInfo.CurrentUICulture.Name } })
#Html.ValidationMessageFor(model => mailModel.PdfMessage)
</div>
</div>
<div class="col-xs-12 padding-bottom-10">
#*<i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF *#
<button type="submit" value="Create" class="btn btn-success" id="btnGeneratePDF" name="btnGeneratePDF" formtarget="_blank" onclick="GeneratePDFFromHtml()"><i class="fa fa-fw fa-check"></i> #Resources.Action.Navigation.GeneratePDF</button>
</div>
</fieldset>
</form>
but the url is now like this, after I press on the button:
http://localhost:51098/Dashboard/Product/Edit/GeneratePDFFromHtml?
what is ofcourse not correct. so how to trigger the method in the controller?
I get also this warning: Uncaught ReferenceError: GeneratePDFFromHtml is not defined
I have created a form using asp.net mvc 5 and when I click the submit button it sucessfully submiting the data. it means it successfully call Create method in my controller. I added
RedirectToAction("Index", "ExaminationManager");
code to last line of the code in Create method. But this not redirect to "Index". It always redirect to "Create".
This is my view code :
#model TutionWeb1.Models.ViewModels.ExaminationManagerVM.ExamViewModel
#using (Html.BeginForm("Create", "ExaminationManager", FormMethod.Post, new { id = "createForm" }))
{
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.SubjectID, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SubjectCategoryID, ViewBag.SubjectCategoriyID as SelectList, "Select a Subject Category", new { id = "SubjectCategory", #class = "form-control" })
#Html.ValidationMessageFor(model => model.SubjectCategoryID)
<br/>
#Html.DropDownListFor(model => model.SubjectID, Enumerable.Empty<SelectListItem>(), "Select a Subject", new { id = "SubjectID", #class = "form-control" })
#Html.ValidationMessageFor(model => model.SubjectID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExamName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ExamName, new { #class = "form-control", placeholder = "Exam Name" })
#Html.ValidationMessageFor(model => model.ExamName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExamNote, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.ExamNote, new { #class = "form-control", placeholder = "Description" })
#Html.ValidationMessageFor(model => model.ExamNote)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EnrollKey, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.EnrollKey, new { #class = "form-control", placeholder = "Enrollment Key" })
#Html.ValidationMessageFor(model => model.EnrollKey)
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</div>
</div>
</div>
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script type="text/jscript">
$(function () {
$('#SubjectCategory').change(function () {
$.getJSON('/ExaminationManager/SubjectsList/' + $('#SubjectCategory').val(), function (data) {
var items = '<option value="">Select a District</option>';
$.each(data, function (i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
$('#SubjectID').html(items);
});
});
});
</script>
Ajax is used to drop down cascade.
This is Create action code :
[HttpPost]
public void Create(ExamViewModel vm)
{
if (ModelState.IsValid)
{
Mapper.CreateMap<ExamViewModel, Examination>();
var exam = new Examination();
Mapper.Map<ExamViewModel, Examination>(vm, exam);
exam.TutorID = KEY_TUTOR_ID;
service_exam.CreateExam(exam);
RedirectToAction("Index", "ExaminationManager");
}
}
EDIT :
Index action:
public ActionResult Index(int? page)
{
var examinationdata = new ExaminationManagerViewModel();
ViewBag.SubjectCategoriyID = new SelectList(service_subject_category.GetSubjectCategories(KEY_LANG), "SubjectCategoryID", "SubjectCategoryName");
IEnumerable<SubjectsResult> subjects_mod = service_subject.GetSubjectsByTutor(KEY_TUTOR_ID,KEY_LANG);
Mapper.CreateMap<SubjectsResult, SubjectListViewModel>();
var subjects = Mapper.Map<IEnumerable<SubjectsResult>, List<SubjectListViewModel>>(subjects_mod);
examinationdata.Subjects = subjects;
IEnumerable<Examination> exams = service_exam.GetExams(KEY_TUTOR_ID).ToList();
Mapper.CreateMap<Examination, ExamRowViewModel>();
var attachments = Mapper.Map<IEnumerable<Examination>, List<ExamRowViewModel>>(exams);
examinationdata.Exam = new ExamViewModel();
examinationdata.Exams = attachments.ToList().ToPagedList(page ?? 1,3);
return View(examinationdata);
}
Its because your Create method is void and returns nothing.
You can try something like this to redirect:
Response.Redirect("/[ControllerName]/[ActionName]");
However, it would be preferable to stick to the MVC pattern,
public ActionResult Create(ExamViewModel vm)