I want to export my Viewmodel from my view to my controller which is receiving it in a method, this is my view:
#using Resources
#model MyProject.ViewModel.CertificationViewModel
#{
ViewBag.Title = Resources.titleCertificationList;
#section css
{
<link href="#Url.Content("~/layout/css/stylesformador.css")" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
}
}
<div class="mainblock">
<div class="block-group">
<div class="ttitle title">#HIQResources.titleEdit</div>
</div>
#using (Html.BeginForm("Edit", "Certification", FormMethod.Post, new { id = "form1" }))
{
#Html.AntiForgeryToken()
<div class="md-content">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.pdf, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#*<input type="file" name="file" />*#
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control inputForm", #type="file" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control inputForm", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedEntityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.SelectedEntityId, Model.EntitiesDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.SelectedEntityId)
#Html.ValidationMessageFor(model => model.SelectedEntityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.StatusId, Model.StatusDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.StatusId)
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Result, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Result, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Result, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Observation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Observation, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Observation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1">
<div class="col-md-8">
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.DisplayNameFor(model => model.FileName)
</th>
<th class="col-md-2">Ficheiro</th>
</tr>
#foreach (var item in Model.teste)
{
<tr>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
#Html.DisplayFor(modelItem => item.FileName)
}
</td>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
Download
#*Delete*#
<input type="submit" value="Edit" id="Delete" class="btn btn-default btn-sm btn-detail" />
}
#*#Html.ActionLink("Download", "Certification", "Download", new { id = Model.Id })*#
</td>
</tr>
}
</table>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<input type="submit" value="#HIQResources.buttonSave" class="btn btn-default btn-sm btn-detail" />
#Html.ActionLink(HIQResources.buttonBack, "CertificationList", new { id = Model.StudentId, nome = Model.StudentName }, new { #class = "btn btn-default btn-sm btn-edit" })
</div>
</div>
</div>
</div>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/HIQTrainingScripts/Certification/Edit.js"></script>
<script>
$("#Date").datepicker({ dateFormat: 'yy/mm/dd' });
$("#Delete").click(function () {
var vm = $('#Model').serialize();
alert(vm)
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Certification/Edit",
type: "POST",
data: {
__RequestVerificationToken: token,
vm: vm,
click: "deu",
},
sucess: function (result) {
alert("sucess");
}
});
});
</script>
}
This is the method in my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CertificationViewModel vm, string click) {
if (click == "deu")
{
int lol = _servicesFactory.GetService<ICertificationManager>().DeleteFile(vm, GetLoggedUser());
return View(vm);
}
}
The value of my ViewModel comes always as null to my Jquery variable and I don't know why, because it should come with the info from the view to the controller in order for me, to execute my task.
Am I missing something ?
Related
I have created a method in the Employee controller for creating a new Employee:
[HttpGet]
[ActionName ("Create")]
public ActionResult Create()
{
return View();
}
I have Added a view for Create method with Employee(strongly-typed)model and used the create template.
When I run the program and click on create new I get a null reference error in create view.
#model BuissnessLayer.Employee
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Employee_Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Salary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Salary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Salary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
I get the error at line
#Html.EditorFor(model => model.Employee_Id, new { htmlAttributes = new { #class = "form-control" } })
I don't know how to solve the problem because the code is created automatically and i haven't edited anything yet.
You should pass model to your View..
[HttpGet]
[ActionName ("Create")]
public ActionResult Create()
{
var model = new Employee(){}
return View(model);
}
#model BuissnessLayer.Employee
I have a view, in the view, I have a section where you can enter the customer account number and then press search
I want the search to query the SQLSERVER for the account number details and retrieve the other details like Name, Account Balance and the likes.
I have finished the View code but I am confused on how to implement the Controller and whether I should use AJAX to ensure that the page does not reload.
Could you advise me?
Below is the View.
#model CreditFacility_Web.Models.CreditFacilityModel.Transaction
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="w3-container" style="padding-left:60px">
#{
ViewBag.Title = "Credit Transaction";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Credit Transaction</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Account_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Account_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Account_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button value="Search" class="btn btn-primary" >Search</button>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Firstname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Firstname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Account_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Account_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Account_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Old_Balance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Old_Balance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Old_Balance, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Amount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.New_Balance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.New_Balance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.New_Balance, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Transaction_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Transaction_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Transaction_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Narration, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Narration, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Narration, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I have been able to work on the View and the Controller and below is what i have.
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$(".btn-primary").click(function () {
var accNo = $('#Account_Number').val();
$.ajax({
url: "#Url.Action("AccountDetails", "Transactions")",
type: "POST",
dataType: "json",
data: { accountNo : accNo },
async: false,
error: function () {
alert('Account Number do not Exist Or Other Errors Occurred');
},
success: function (data) {
if (Object.keys(data).length > 0) {
$('#Firstname').val(data.Firstname);
$('#Old_Balance').val(data.Account_Balance);
}
}
});
});
});
</script>
}
And the Controller has the below.
[HttpPost]
public ActionResult AccountDetails(string accountNo)
{
using (var db = new CreditFacilityContext())
{
var accDetails = db.SavingsAccounts.Where(t => t.Account_Number == accountNo).Select(s => new SavingsAccount
{
Firstname = s.Firstname,
Account_Balance = s.Account_Balance,
//rest of properties
}).FirstOrDefault(); ;
return Json(accDetails, JsonRequestBehavior.AllowGet);
}
}
Ajax method to retrieve data without page refresh:
$(".btn-primary").click(function () {
var accNo = $('#Account_Number').val();
$.ajax({
url: "#Url.Action("AccountDetails", "Home")",
type: "POST",
dataType: "json",
data: { accountNo : accNo },
async: false,
error: function () {
},
success: function (data) {
if (Object.keys(data).length > 0) {
$('#Firstname').val(data.FirstName);
$('#Old_Balance').val(data.Balance);
}
}
});
});
Home Controller code to fetch data from SQL Server:
[HttpPost]
public JsonResult AccountDetails(string accountNo)
{
using (DBContextModel dataContext = new DBContextModel())
{
var accSearchParameter = new SqlParameter("#Search", accountNo);
var accDetails = dataContext.Database.SqlQuery<AccDetails>("EXEC YourStoredProc #Search", accSearchParameter ).Select(s => new AccDetails
{
FirstName = s.FirstName,
Balance = s.Balance,
//rest of properties
}).SingleOrDefault();
return Json(accDetails, JsonRequestBehavior.AllowGet);
}
}
Pre-requisites for the Controller code to work:
Stored procedure
AccDetails class with properties that match the select column names/aliases of SP. Try this, I think you probably need to read up on jQuery Ajax and JSON in MVC.
I have a form for adding Books in a database,
I Have a modal window in my form to create a Publisher, if the specified format doesn't exist in Publisher Dropdown, I Create my Modal in a partial view for add Publisher,
this is my view:
#model WebApplication3.Models.BookModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="CustomerList"></div>
<h2>Create New Book</h2>
<label class="text-#ViewBag.ClassName">
#ViewBag.Message
</label>
#using (Html.BeginForm("CreateBook", "Book", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TitleID, "TitleID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TitleID", null, "Select a Title", htmlAttributes: new { #class = "form-control" })
#Html.ActionLink("Add New", "Create", "Title")
#Html.ValidationMessageFor(model => model.TitleID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FormatID, "FormatID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FormatID", null, "Select a Format", htmlAttributes: new { #class = "form-control" })
<a href="" class="" data-toggle="modal" data-target="#FormatModal">
Add New
</a>
#Html.ValidationMessageFor(model => model.FormatID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ISBN, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ISBN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ISBN, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="PublisherModal" tabindex="-1" role="dialog" aria-labelledby="publisherModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
#Html.Partial("_Publisher")
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryajax")
}
and this is my Publisher partial view:
#model WebApplication3.Models.PublisherModel
#using (Ajax.BeginForm("CreatePublisher", "Book", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "publisherForm", InsertionMode = InsertionMode.ReplaceWith }))
{
<div id="publisherForm">
<div class="modal-header">
<h5 class="modal-title" id="publisherModalLongTitle">Create New Publisher</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<span class="text-#ViewBag.ClassName">
#ViewBag.Message
</span>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Value, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Value, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
#Html.ActionLink("Manage", "Index", "Publisher", new { area = "" }, new { #class = "btn btn-link" })
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
}
and this is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CreatePublisher([Bind(Include = "ID,Value,Description")] PublisherModel publisherModel)
{
ViewBag.TitleID = new SelectList(repoTitle.GetModels(), "ID", "Title");
ViewBag.FormatID = new SelectList(repoFormat.GetModels(), "ID", "Value");
PublisherModel publisher = repoPublisher.GetModels().FirstOrDefault(x => x.Value == publisherModel.Value);
if (publisher == null)
{
if (ModelState.IsValid)
{
repoPublisher.Insert(publisherModel);
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value", publisherModel.ID);
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Added Successfully";
ViewBag.ClassName = "success";
return PartialView("_Publisher");
}
}
else
{
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Already Exsisted";
ViewBag.ClassName = "danger";
}
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value");
return PartialView("_Publisher",publisherModel);
}
How Can change to my code that if a new Publisher inserted to Database, the Publisher dropdown refresh and select newly inserted data as a selected item?
About question
I can't run your code locally.
These operations can be implemented through JS.
I can show my tools.
This is the function gif:
Solution:
Select and add options as a whole.
// index.cshtml
<div>
#await Component.InvokeAsync("AutoAddListValue")
</div>
//Component
#model List<string>
<h3>Default page</h3>
<div>
<div>
<p>Lists</p>
<select name="select" class="" id="ComponentSelectId" onclick="ComponentSelectClick()">
<option id="ComponentOptionId" style="width:auto">ComponentTest</option>
#if (Model.Count != 0)
{
int count = Model.Count();
for (int item = 0; item < count; item++)
{
<option id="option">#Model[item].ToString()</option>
}
}
</select>
</div>
<div>
<input id="ComponentTestJsInput" class="d-none" value="132323" type="text" />
<input id="ComponentBtnDisplay" value="Add" type="button" class="btn btn-primary" onclick="ComponentBtnDisplayClick()">
<input id="ComponentBtnAdd" value="Add" type="button" class="btn btn-primary d-none" onclick="ComponentBtnAddClick()">
</div>
</div>
Bind data for components.
public class AutoAddListValueViewComponent : ViewComponent
{
private readonly SchoolContext _context;
public AutoAddListValueViewComponent(SchoolContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(
int maxPriority, bool isDone)
{
string MyView = "Default";
var items = await GetListAsync();
return View(MyView, items);
}
public async Task<List<string>> GetListAsync()
{
return await _context.Test.Select(o => o.Name).ToListAsync();
}
}
Using JS code to realize page interaction.
var ComponentBtnDisplayClick = function () {
$('#ComponentBtnAdd').removeClass("d-none");
$('#ComponentTestJsInput').removeClass("d-none");
$('#ComponentBtnDisplay').addClass("d-none");
}
var ComponentBtnAddClick = function () {
//alert("666666");
$('#ComponentBtnAdd').addClass("d-none");
$('#ComponentTestJsInput').addClass("d-none");
$('#ComponentBtnDisplay').removeClass("d-none");
inputVal = $('#ComponentTestJsInput').val();
//alert(inputVal);
$.ajax({
url: '/Test/SaveInputValue',
data: {
name: inputVal
},
type: 'post',
async: true,
cache: false,
success: function (data) {
//alert(data.code);
var option = "<option id='ComponentOptionId'>";
option += inputVal;
option += "</option>";
$("#ComponentSelectId").append(option);
var obj = document.getElementById("ComponentSelectId");
obj[obj.length - 1].selected = true;
},
error: function () {
alert('fail');
}
});
}
Other code
Source Code
#model CommonLayer.ORDER
#{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Update Order Status</h4>
<br />
#if (Model.OrderStatus != "Shipped")
{
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.LabelFor(model => model.OrderId, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderId, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderStatus, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
<select class="form-control" name="OrderStatus">
<option value="Pending" id="pending">Pending</option>
<option value="Shipped" id="shipped">Shipped</option>
</select>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDate, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderNumber, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderNumber, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<form action="/order/update/#Model.OrderId" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
</form>
</div>
}
}
else
{
<h4>Order Has Been Shipped!</h4>
}
My submit button isn't working regardless of the correct syntax being used. When I press the button nothing happens, as if I haven't clicked it, no redirecting whatsoever.
Was working until yesterday. Did not change any code whatsoever regarding the form or corresponding controller.
This is the controller corresponding to the form.
[HttpGet]
[Authorize(Roles = "ADM")]
public ActionResult Update(Guid Id)
{
BusinessLayer.Orders order = new BusinessLayer.Orders();
return View(order.GetOrder(Id));
}
[HttpPost]
[Authorize(Roles = "ADM")]
public ActionResult Update(CommonLayer.ORDER order, Guid id)
{
BusinessLayer.Orders blorder = new BusinessLayer.Orders();
blorder.UpdateOrder(order);
return RedirectToAction("UpdateDetails", new {id=id});
}
Use below code, let us know if doesn't work
Added below line to pass the orderid
#Html.HiddenFor(model => model.OrderId)
Updated below line to call action of a controller
Html.BeginForm("update","order",FormMethod.Post)
Finally removed the unnecessary form tag
Removed antiforgerytoken from view as you are not checking in you action method.
If you want to add that then you need to add [ValidateAntiForgeryToken] after [httppost] of Update Action method
#model CommonLayer.ORDER
#{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Update Order Status</h4>
<br />
#if (Model.OrderStatus != "Shipped")
{
using (Html.BeginForm("Update","Order",FormMethod.Post))
{
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
#Html.HiddenFor(model => model.OrderId)
<div class="form-group">
#Html.LabelFor(model => model.OrderId, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderId, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderStatus, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
<select class="form-control" name="OrderStatus">
<option value="Pending" id="pending">Pending</option>
<option value="Shipped" id="shipped">Shipped</option>
</select>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDate, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderNumber, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderNumber, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
</div>
}
}
else
{
<h4>Order Has Been Shipped!</h4>
}
My view is shown below:
#model KtembRegistry.Models.Entities.Member
#{
ViewBag.Title = "Üye Güncelleme";
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.MemberId)
#Html.HiddenFor(model => model.Director.EmployeeId);
<div class="form-horizontal">
<hr />
<div class="form-group">
<input type="button" value="Back to List" onclick="location.href='#Url.Action("Index", "Members")'" class="btn btn-primary" />
<input type="submit" value="Save" class="btn btn-success" />
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.MemberName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MemberName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Location, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.MemberClass, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MemberClass, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MemberClass, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClassId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClassId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClassId, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.LastApprovalDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastApprovalDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastApprovalDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TaxNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TaxNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TaxNo, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fax, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fax, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fax, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<br />
<h4>Direktör</h4>
<hr />
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Director.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Director.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.LastName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Director.IdentityNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.IdentityNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.IdentityNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Director.Responsibility, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.Responsibility, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.Responsibility, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<br />
<h3> Personel </h3>
<hr />
<table class="table table-hover">
<thead>
<tr>
<th>İsim</th>
<th>Kimlik No</th>
<th>Yetki</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Employees)
{
<tr>
<td>#item.FirstName</td>
<td>#item.IdentityNo</td>
<td>#item.Responsibility</td>
<td>
#Html.ActionLink("Edit", "Edit", new { #item.EmployeeId }) |
#Html.ActionLink("Delete", "Delete", new { #item.EmployeeId })
</td>
</tr>
}
</tbody>
</table>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Entity:
public class Employee
{
public virtual int Id { get; protected set; }
public virtual int EmployeeNo { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual int IdentityNo { get; set; }
public virtual string Responsibility { get; set; }
public virtual Member Company { get; set; }
}
When I do post, everything is sent to controller just fine except model.Director.EmployeeId. The controller sends the EmployeeId field correctly to the field. Whatever, I do it does not work. Any ideas why my post does not work ?
I have an old habit of making the setter of identity fields in my entities protected in order to protect outside mangling. However, in this case it was causing the identity field from being updated which was the cause of the problem.