Html.BeginForm FormMethod.Post submit button click not working? - c#

Single page having three different registration form,based on single ID reference, I need to call the three different [HttpPost] ActionResult method ,when i click the submit button for first form it's goes to first action result method correctly.
<div class="page-content">
<div class="container-fluid">
<header class="section-header">
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<h2>Company Registration Form</h2>
</div>
</div>
</div>
</header>
#using (Html.BeginForm(FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<section class="tabs-section">
<div class="tabs-section-nav tabs-section-nav-icons">
<div class="tbl">
<ul class="nav" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="#tabs-1-tab-1" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="font-icon font-icon-cogwheel"></i>
Company Registration Form
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-2" role="tab" data-toggle="tab">
<span class="nav-link-in">
<span class="glyphicon glyphicon-music"></span>
Company Social Network
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-3" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="fa fa-product-hunt"></i>
Company Reference
</span>
</a>
</li>
</ul>
</div>
</div><!--.tabs-section-nav-->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active show" id="tabs-1-tab-1">
<br />
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model =>Model.company.CompanyName, new { #class = "form-label semibold control-label" })
#Html.TextBoxFor(model => model.company.CompanyName, new { #class = "form-control", placeholder = "Enter the Company Name" })
#Html.ValidationMessageFor(model => model.company.CompanyName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.ShortName, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.ShortName, new { #class = "form-control", placeholder = "Enter the Short Name" })
#Html.ValidationMessageFor(model => model.company.ShortName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Division, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Division, new { #class = "form-control", placeholder = "Enter the Division" })
#Html.ValidationMessageFor(model => model.company.Division)
</fieldset>
</div>
</div><!--.row-->
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Email, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Email, new { #class = "form-control", placeholder = "Enter your Email" })
#Html.ValidationMessageFor(model => model.company.Email)
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" id="Save" value="Save" class="btn btn-rounded btn-inline btn-success" onclick=" GetInfo();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-2">
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.FaceBookID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.FaceBookID, new { #class = "form-control", placeholder = "Enter the Facebook Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.TwitterID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.TwitterID, new { #class = "form-control", placeholder = "Enter the Twitter Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.linkedinID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.linkedinID, new { #class = "form-control", placeholder = "Enter the Linkedin Link" })
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" id="Save" value="Next" class="btn btn-rounded btn-inline btn-success" onclick="GetInfo1();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-3">
Tab 3
<br /><br />
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" value="Finish" class="btn btn-rounded btn-inline btn-success" />
</div><!--.tab-pane-->
</div><!--.tab-content-->
</section><!--.tabs-section-->
}
</div>
</div>
ActionResult Code:
[HttpPost]
public ActionResult AddCompany(MainModel cmp)
{
try
{
if (ModelState.IsValid)
{
}
return View();
}
catch
{
return View();
}
}
When i click second Submit button it's again going to the same ActionResult AddCompany(MainModel cmp) but i need to go to ActionResult AddSocial(MainModel Social)
Here this code :
[HttpPost]
public ActionResult AddSocial(MainModel Social)
{
try
{
if (ModelState.IsValid)
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "paginationClickHandler", "paginationClickHandler();", true);
}
return View();
}
catch
{
return View();
}
}
Ajax Method:
function GetInfo() {
var company = { companyName: document.getElementById('CompanyName').value, shortName: document.getElementById('ShortName').value, division: document.getElementById('Division').value, Email: document.getElementById('Email').value }
$.ajax({
type: "POST",
url: "/Company/AddCompany",
data: '{cmp:' + JSON.stringify(company) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
function GetInfo1() {
var Social = { faceBook: document.getElementById('FaceBook').value, twitter: document.getElementById('Twitter').value, linkedin: document.getElementById('linkedin').value }
$.ajax({
type: "POST",
url: "/Company/AddSocial",
data: '{Social:' + JSON.stringify(Social) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}

Your button is still inside a form. So when you handle your button click in javascript, you need to make sure to prevent the default behavior of a submit button click inside a form ( the form submit).
Using unobtrusive javascript way, give a unique id to your button
<input type="submit" id="saveSocial" value="Next" />
and now, bind click event on this button, prevent the default behavior using
jquery preventDefault method and call your js method.
$(document).ready(function() {
$("#saveSocial").click(function(e) {
e.preventDefault();
GetInfo1();
});
});
Also it does not make sense to return a full view from your action method when the call is from ajax code. May be you should return a json response.

A submit inside the form is going to post the form, even if you have an onclick action written. If you want it to instead call the javascript function, change the <input> to a <button> or <a> tag.
EDIT
Delete the form tag completely to prevent submission which is reloading your page.

Related

more than 1 HttpPost is activating

I am making a page where I'd like to be able to have several different actions happening depending on what is being done.
for instance I have a dropdown where I want different forms to be loaded in to the page depending on the selection in the dropdown.
Currently I'm doing it like this:
$(document).ready(function () {
$('#subject').on("change", function (e) {
e.preventDefault();
var selectedVal = $('#subject').val();
$.ajax({
url: "ContactUs/GetForm",
type: "POST",
data: { searchValue: selectedVal },
async: true,
success: function (data) {
$('#renderForms').empty();
$('#renderForms').append(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("An error has occured!!! " + xhr.status + " && " + xhr.responseText);
}
});
}; etc...
this hits the following method no problem
[HttpPost]
public ActionResult GetForm(string searchValue)
{
//my code here
return PartialView("_Bills",contactModel.contactBillsModel);
}
However when I click on it also hit the following method which is not my intention.
[HttpPost]
public ActionResult Index(Contact_Portal.Models.ContactViewModel contactModel)
{
return View(contactModel);
}
How do I prevent this behaviour ?
the last HttpPost I'm using in a button in the partial page like this
<input id="Send" type="submit" value="Send" class="btn btn-default" />
Edit:
Adding Additional Information per requested.
the view with the dropdown
#model WebPortal.Models.FormViewModel
#{
ViewBag.Title = "multiple forms";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>multiple forms</h2>
<label>My selection is... </label>
#Html.DropDownListFor(model => model.contactSelectListItems, new List<SelectListItem>
{
new SelectListItem() {Text = "option 1", Value="option 1"},
new SelectListItem() {Text = "option 2", Value="option 2"},
new SelectListItem() {Text = "option 3", Value="option 3"},
new SelectListItem() {Text = "option 4", Value="option 4"}
}, "--choose--", new { id = "subject", #class="dropdown-item"})
<div id="renderForms">
</div>
one of the views with the forms:
#model WebPortal.Models.AformViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>A Form</h4>
<hr />
<div id="InfoBox" class="form-group col-md-20">
Remember to fill out this text with relevant text.
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="container">
<div class="row">
<div class="form-group form-group-sm col-sm-6">
<div class="row">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-9">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group form-group-sm col-sm-6">
<div class="row">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-9">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<div class="col-sm-9">
<!--#Html.Action("Index", "ContactUs")-->
<input id="Send" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
Well I have a solution thou I'm not really happy with it but it works.
this is what I've done since posting my question:
I've changed on request from Stephen Muecke this part here:
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<div class="col-sm-9">
<!--#Html.Action("Index", "ContactUs")-->
<input id="Send" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
to
<div class="form-group form-group-sm col-sm-6">
<div class="row">
<div class="col-sm-9">
<input id="Send" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
and after that It removed my problem with activating both my HttpPost Actions GetForm and Index(viewmodel)
but I got the new problem of the submit button activating the GetForm action instead of the Index(viewmodel) action.
So because of this I changed my submit button to the following
<input id="Send" type="submit" value="Send" formaction=#Url.Action("Index","ContactUs") class="btn btn-default" />
this change solved my problem for now but I feel that the input submit button now is now not inline with the ideas behind unobtrusive event handling.
Edit:
instead of the above submit button line I added this to the html form:
#using (Html.BeginForm("Index", "ContactUs"))
The problem is that your input with type="submit" is submitting the form. This is the standard behaviour for HTML-forms.
Change the input's type to type="button":
<input id="Send" type="button" value="Send" class="btn btn-default" />
Then change the event in jQuery to "click":
$(document).ready(function () {
$('#subject').on("click", function (e) {
e.preventDefault();
var selectedVal = $('#subject').val();
$.ajax({
url: "ContactUs/GetForm",
type: "POST",
data: { searchValue: selectedVal },
async: true,
success: function (data) {
$('#renderForms').empty();
$('#renderForms').append(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("An error has occured!!! " + xhr.status + " && " + xhr.responseText);
}
});
}; etc...

Popup partial view in a bootstrap model popup

#Html.ActionLink("edit", "Edit", "MedQuantityType", new { id = item.Med_quan_typeId }, new
{
#* Needed to link to the html of the modal*#
data_target = "#mymodel",
#* Tells the bootstrap javascript to do its thing*#
data_toggle = "modal",
})
This the action link I try to popup partial view in bootstrap model, it's working fine when I try to edit & save it works except model state is not valid
here my controller code
public async Task<ActionResult > Edit([Bind(Include = "Med_quan_typeId,Med_quan_type,Med_quantity")] Med_quantity_type med_quantity_type)
{
if (ModelState.IsValid)
{
db.Entry(med_quantity_type).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return PartialView(med_quantity_type);
}
If my model state fails the controller return partial view but its not popup in mymodel this is my partial view cshtml page
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Medicine Quantity Type - Edit</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Edit", "MedQuantityType",
new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "mymodel"
}))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Med_quan_typeId)
<div class="form-group">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Med_quan_type, new { #class = "control-label " })
</div>
<div class="col-md-6">
#Html.TextBoxFor(model => model.Med_quan_type, new { #class = "form-control", #id = "txtquantype" })
#Html.ValidationMessageFor(model => model.Med_quan_type)
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Med_quantity, new { #class = "control-label" })
</div>
<div class="col-md-6">
#Html.TextBoxFor(model => model.Med_quantity, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Med_quantity)
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Save" class="btn btn-success" id="btnsubmit" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
<div ID ="popupform"class="popover">
<div class="alert-danger"> Please Fix The errors </div>
</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
debugger;
// when the modal is closed
$('#mymodel').on('hidden.bs.modal', function () {
// remove the bs.modal data attribute from it
$(this).removeData('bs.modal');
// and empty the modal-content element
$('#mymodel .modal-content').empty();
});
});
});
</script >
Please help anyone how to popup partial view, once controller return partial view
From Task<ActionResult > to Task<PartialViewResult> then change your ActionLink to RenderPartial.
It should work fine.
Change the return type of your action to Task<PartialView>

Working with attribute routing in mvc

On my login page I have a dropdownlist to change the culture of the application for which I am doing a Ajax call to set the culture. By default I have set to 'en_US'.
My issue is when I am login directly without changing the culture I am able to login successfully, but when I change the culture and tries to login, I am not able to do that. Is this happening because of AJAX call made, which makes custom attribute not registered ?
Also, my login method has a custom attribute defined. Below is the code.
AJAX Call
$('#ddlLanguages').change(function () {
var val = $('#ddlLanguages').val()
createCookie('culturecookie', val, 7);
$.ajax({
type: "POST",
url: '/Account/GetCultureNew',
data: { culturename: val },
success: function (result) {
$("#logo-group").html('');
$(document.body).html('');
$(document.body).html(result);
},
error: function (data) {
//alert('Error');
}
});
});
Ajax Method in controller
[HttpPost]
public ActionResult GetCultureNew(string culturename)
{
if (!string.IsNullOrEmpty(culturename) & culturename.Contains("#"))
{
string[] strdata = culturename.Split('#');
if (strdata.Length > 0)
{
AppTenant tenant = HttpContext.Session.GetObjectFromJson<AppTenant>("TenantInfo");
if (tenant != null)
{
tenant.LoggedInCulture = strdata[0];
tenant.LanguageID = Convert.ToInt32(strdata[1]);
HttpContext.Session.SetObjectAsJson("TenantInfo", tenant);
}
}
}
List<SelectListItem> items = new List<SelectListItem>();
items = HttpContext.Session.GetObjectFromJson<List<SelectListItem>>("LanguageData");
foreach (var item in items)
{
if (item.Value == culturename)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
var itemsString = JsonConvert.SerializeObject(items);
CookieOptions obj = new CookieOptions();
obj.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Append("Languagelist", itemsString, obj);
var viewModel = new LMS_User { ReturnUrl = string.Empty, LanguageList = items };
return View("Login", viewModel);
}
Login Method
[HttpPost]
[AllowAnonymous]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route("Admin/Login/{clietname}")]
public async Task<IActionResult> Login([Bind(include: "Email,Password,RememberMe")] LMS_User model, string returnUrl)
{
// my login logic
}
EDIT :- 1
Login partial View
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-4">
<div class="well no-padding">
<form action="#Url.Action("login", "account")" method="POST" id="login-form" class="smart-form client-form">
<header>
#obj["SingnIn"]
</header>
#Html.AntiForgeryToken()
<fieldset>
<section>
<label asp-for="LanguageList">#obj["LanguageList"] </label>
#Html.DropDownList("Languages", Model.LanguageList, null, new { id = "ddlLanguages", #class = "form-control" })
</section>
<section>
<label asp-for="Email">#obj["Email"]</label>
<label class="input">
<i class="icon-append fa fa-user"></i>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i>>#obj["tooltipEmail"]</b>
<span asp-validation-for="Email" class="text-danger"></span>
</label>
</section>
<section>
<label asp-for="Password">#obj["Password"]</label>
<label class="input">
<i class="icon-append fa fa-lock"></i>
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-lock txt-color-teal"></i>#obj["tooltippassword"] </b>
<span asp-validation-for="Password" class="text-danger"></span>
</label>
<div class="note">
<i class="fa fa-frown-o"></i> #obj["Forgot_password?"]
</div>
</section>
<section>
<label class="checkbox">
<input asp-for="RememberMe" />
<i></i>#obj["Remember_Me"]
</label>
</section>
<footer>
<button type="submit" class="btn btn-primary">
#obj["SingnIn"]
</button>
</footer>
</fieldset>
</form>
</div>
#{ await Html.RenderPartialAsync("_SocialMedia"); }
Edit 2:-Entire login view
<div id="content" class="container">
<div class="row">
#{ await Html.RenderPartialAsync("_LoginText"); }
#{ await Html.RenderPartialAsync("_LoginPartial"); }
</div>
</div>
However if I add location.reload() in AJAX success function, then by changing the culture I can login successfully.
Any help on this appreciated !
When you do the $(document.body).html(result);
The action part of the form goes missing. Hence it does not know where to post to.
Hope i have been of some help :)

return 2 values to controller, text remains NULL

trying to pass 2 values back to the controller id', and 'text'...id passes ok but text always returns nulll any idea why?
<div class="modal-body">
<input type="hidden" id="AlertFreeTextId" name="AlertFreeTextId" value="#Model.AlertFreeTextId" />
<input type="hidden" id="Text" name="Text" value="#Model.Text" />
<div class="form-group">
#Html.LabelFor(x => x.Text)
#Html.TextAreaFor(x => x.Text, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Text)
</div>
<div>
<a href='#Url.Action("CreateAlertFreeText", "AlertFreeText", new { id = Model.AlertFreeTextId, text = Model.Text})'>
<button class="btn btn-primary">#T("Save")</button>
</a>
</div>
</div>
//controller
public ActionResult CreateAlertFreeText(int id, string text)
{
}
This line here:
<a href='#Url.Action("CreateAlertFreeText", "AlertFreeText", new { id = Model.AlertFreeTextId, text = Model.Text})'>
All this is doing is getting the text that was passed into the View. I assume when you call the view, Model.Text is null, so that's exactly what it's returning.
You need to pull the data from the form when you submit like that.
I'd suggest creating either using a form post, or calling a jquery method to do the post where you can pull the form data.
Maybe something like this: (warning: untested!)
<div class="modal-body">
<input type="hidden" id="AlertFreeTextId" name="AlertFreeTextId" value="#Model.AlertFreeTextId" />
<input type="hidden" id="Text" name="Text" value="#Model.Text" />
<div class="form-group">
#Html.LabelFor(x => x.Text)
#Html.TextAreaFor(x => x.Text, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Text)
</div>
<div>
<a href='#' id='alertFreeTextLink'>
<button class="btn btn-primary">#T("Save")</button>
</a>
</div>
</div>
<script>
$(document).ready(function() {
$("#alertFreeTextLink").click(function() {
var url = '#Url.Action("CreateAlertFreeText", "AlertFreeText",
new { id = Model.AlertFreeTextId })';
url = url + "&text=" + $("#Text").val();
$.ajax({
url: url
})
.done(function(response) {
/// Do something here
});
});
});
</script>

MVC Model is empty when postback

I have this model, Customer . When i get the information with an id, it works just fine.
Like ;
/Customer/Entity/5
#model ProgSpace.Models.Customer
#{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_MainLayout.cshtml";
}
#section bodypane
{
#using (Html.BeginForm("Entity", "Customer", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12">
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4>
</div>
<div class="clearfix"></div><br />
<div class="col-md-2">
<div class="col-md-12">
<div class="col-md-12 fileupload fileupload-exists" data-provides="fileupload">
<div class="fileupload-preview fileupload-exists thumbnail" style="width: 200px; height: 150px;">
<img src="#Model.Picture.Path" />
</div>
<div>
<span class="btn btn-default btn-file">
<span class="fileupload-new">Add Pic </span>
<span class="fileupload-exists">Change</span><input name="file" id="file" type="file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="col-md-10">
<div class="col-md-3">
<label>Name *</label>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Company</label>
#Html.TextBoxFor(model => model.Contact.Company, new { #class = "form-control"})
</div>
<div class="col-md-3">
<label>Phone </label>
#Html.TextBoxFor(model => model.Contact.Phone, new { #class = "form-control" })
</div>
</div>
<div class="clearfix"><br /></div>
<p> </p>
<div class="col-md-12">
<div class="btn-group">
<button class="btn btn-danger btn-lg">Cancel</button>
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</div>
}
}
And in the controller i have these actions.
public ActionResult Entity(int id)
{
Customer cust= sis.Customers.Where(t => t.ID == id).FirstOrDefault();
return View(cust);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Entity(Customer cust, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
/* Do something */
}
else
{
}
return View(cust);
}
When the verb is GET , it's fine. But when i post this form and when the second action (HttpPost action) kicks in , view throws an error..
Object reference not set to an instance of an object
which marks the Model.ID is null in the view.
<div class="col-md-1">
<label>Customer No:</label>
<h4># #(Model.ID) </h4> ---> THIS HERE THROWS NULL EXCEPTION
</div>
I've tried to add a HiddenFor for the Model.ID like
#Html.HiddenFor(t => t.ID)
but it didn't change anything.
How do i get back to the same view with the same context again ?

Categories