Retrieving ViewModel data collection is null - c#

I am passing model from view to controller. in my viewmodel List<TradeLaneDetailsDTO> is null always, and i am passing my data through ajax. what is the problem in my code.
please help me...
here is my viewmodel
public class SLAViewModel
{
public List<TradeLaneDetailsDTO> Items { get; set; }
}
here is my view
#using (Html.BeginForm("SaveSLA", "SLAMgmt", FormMethod.Post, htmlAttributes: new { #class = "form-horizontal", #role = "form", id = "frmEstDays" }))
{
for (int i = 0; i < Model.Items.Count; i++)
{
<div class="form-group">
#Html.LabelFor(model => model.Items.ElementAt(i).legname, Model.Items.ElementAt(i).legname, new { #class = "col-md-4" })
<div class="col-md-3">
#Html.TextBoxFor(model => model.Items.ElementAt(i).estddays, new { #class = "form-control", type = "text", MaxLength = "10" })
</div>
</div>
}
<div class="form-group">
<div class="offset-3 col-md-8">
<button id="btnSave" type="button" title="Save" class="btn btn-success" onclick="getPage1('#Url.Action("SaveSLA", "SLAMgmt")')">
<span class="glyphicon glyphicon-floppy-disk"></span>Save
</button>
</div>
</div>
}
and here is my ajax function
function getPage1(page)
{
alert("get page1");
$.ajax({
type: "POST",
url: page,
data: $("#frmEstDays").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
alert(html.responseText);
},
error: function (data) {
var error = "Error ";
}
});
}
here is my controller functions
public ActionResult SaveSLA(SLAViewModel slavModel)
{
string[] ErrorMessageArray = new string[4];
int errorIndex = 0;
return anything;
}

Simply use model=>model.Items[i].PROPERTYNAME as below
#Html.TextBoxFor(model => model.Items[i].estddays, new { #class = "form-control", type = "text", MaxLength = "10" })
hope this will help

Please remove type = "text" from TextBoxFor html helper.
#Html.TextBoxFor(model => model.Items.ElementAt(i).estddays, new { #class = "form-control", MaxLength = "10" })
The HtmlTextboxFor always creates a textbox <input type="text" />. So you don't have to specify explicitly.

Related

html helper don't get values back from controller after ajax.beginform

I have a ajax.beginform that I have to upload a file and then in the view I have hidden for the path of the file that have been
saved in the server.
The problem is that the value of the path doesn't return to the view after the the post call.
I am returning new partial view with the errors and the value don't
coming
please help me
post method from controller that return partial view
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSocioDetails(SpSocio socio) // ajax for 1 step in socio
{
bool sociook = false;
socio.StudentId = sStudentId; // bind student id to socio model
socio = SocioDetValid(ref sociook,socio);
// add validation
if (ModelState.IsValid && sociook)
{
socio = SaveSocioModel(socio);
Response.StatusCode = 200;
}
else
Response.StatusCode = 300; // return error to client the model is not valid
return PartialView("~/Views/Student/Socio/SocioDetails.cshtml", socio); // return the partial view of the forn with validation messages
}
Sociodetvalid function that saves the file and add the path to path field:
// bank account validation and save
if (socio.FileBankAccount == null) // if there is no file
{
if (socio.PathBankAccount == null) // check if he upload file already - if not add error message
{
ModelState.AddModelError("FileBankAccount", "חובה לצרף קובץ");
ok = false;
}
}
else // upload new the file
socio.PathBankAccount = Files.SaveFileInServer(socio.FileBankAccount, "BankAccount", sStudentId, socio.PathBankAccount);
the section in view for upload and the hidden for the path string:
<div class="row">
<div class="col-xl-3 col-lg-3 col-md-4 col-12 ">
#Html.LabelFor(model => model.BankStatus, htmlAttributes: new { #class = "control-label col-12" })
#Html.EditorFor(model => model.BankStatus, new { htmlAttributes = new { #class = "form-control must m-1 mt-0" } })
#Html.ValidationMessageFor(model => model.BankStatus, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PathBankAccount)
</div>
<div class="col-xl-3 col-lg-3 col-md-4 col-12">
#Html.LabelFor(model => model.FileBankAccount, htmlAttributes: new { #class = "control-label col-12 must-sign", #for = "" })
<div class="chose-file m-1 mt-0">
#Html.TextBoxFor(model => model.FileBankAccount, new { #class = "form-control must", #type = "file", #accept = "image/jpeg,image/jpg,image/png,application/pdf", #style = "display:none;" })
<label for="FileBankAccount">
<i class="ml-1 material-icons">add_photo_alternate</i>
בחר קובץ
</label>
</div>
#Html.ValidationMessageFor(model => model.FileBankAccount, "", new { #class = "text-danger" })
</div>
#*
<div class="col-xl-3 col-lg-3 col-md-4 col-12" style="display:#(Model.PathBankAccount != null ? "" : "none")">
<label class="control-label col-12" for="">קובץ שמור</label>
<a name="#Model.PathBankAccount" class="btn btn-light btn-file m-1 mt-0">צפייה בקובץ שמור</a>
</div>*#
Thanks for help
Update:
Ajax form code : this is the part of the ajax that in a big view
<fieldset>
#using (Ajax.BeginForm("SaveSocioDetails", "Student", new AjaxOptions { HttpMethod = "POST", OnSuccess = "firstsuccess",OnFailure = "sociodetailsfail", UpdateTargetId="partialsocio" ,LoadingElementId = "div_loading" }, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div id="partialsocio">
#Html.Action("PartialSocioDetails", "Student", new { SpId = ViewBag.SpId })
</div>
<div id="div_loading" style="display:none;">
<img src="#Url.Content("~/Content/Pic/Spinner.gif")" alt="" />
</div>
<button class="btn btn-primary" type="submit">המשך</button>
}
<input type="button" name="next" class="next action-button bg-primary" hidden value="Next" id="sociodetnext" />
</fieldset>
this is the function of fail and success ajax:
<script>
$(document).ready(function ()
{
});
function firstsuccess() {
console.log('this is ajaxSuccess');
$("#sociodetnext").click();
}
function sociodetailsfail(bdata) {
console.log('this is ajaxfail');
console.log(bdata.responseText);
$('#partialsocio').html(bdata.responseText);
}
</script>
In the script that Have returned to the client the value of the string doesn't appear..
Thanks for help

Display value from controller based on two dropdown selection on the view(when select both of them at the same time). MVC asp.net

On the product output insert page, when user select from two dropdown lists(depoId and materialId) at the same time, I would like to display the stock quantity (stockAmount) of the product with the help of material id and the depot id. I do not know how I display on the view part and how I write based on two dropdownlist selection.
Create.cshtml
#model StockControl.Models.EntityFramework.OutgoingProduct
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.materialId, "Material Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("materialId", null, htmlAttributes: new { #class = "form-control chosen" })
#Html.ValidationMessageFor(model => model.materialId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.depoId, "Product Outlet", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("depoId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.depoId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-success" />
</div>
</div>
</div>
}
#section scripts{
<script>
$(function () {
$('.chosen').chosen();
});
$("#materialId", "#depoId").change( function (event) {
var materialId = $(this).val();
var depoId = $(this).val();
$.ajax({
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: { id : materialId, id: depoId },
type: "Get",
dataType: "html",
success: function (data) {
document.write(model.stockAmount);
$("#divPartialView").html( data );
}
});
});
</script>
}
use ajax to send these id to controller
import jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
listen the select change event and send data to controller
<script type="text/javascript">
$(document).ready(function () {
$('#depoId').change(function () { sendDataByAjax(); });
})
function sendDataByAjax() {
// make sure two dropdownlists have selected option
var materialId= $('#materialId option:selected').val();
var depoId= $('#depoIdoption:selected').val();
if (!materialId || !depoId) {
// one of dropdownlist doesn't select an option yet
}
var DTO = {
'materialId': materialId,
'depoId': depoId
};
$.ajax({
type: "POST",
url: "#Url.Action("GetStock", "OutgoingProduct")",
data: JSON.stringify(DTO),
contentType: "application/json",
success: function (data) {
// append data into your target part of view
}
});
}
</script>

asp.NET mvc, get model list values from view

I am new to mvc and am trying to do something like in the below image (im not using partial views).
I have an IEnumerable property on Model
Like in this image, (i have not enough reputation to show image directly)
but on controller if i put FormCollection as parameter to accepting post method when i process same name fields i get an extra character ',', which might be also used by user...
Any idea....
[EDIT]
My view
#model Models.Question
#{
ViewBag.Title = "Add";
}
<h2>Add</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Question</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.SurveyId)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.QuestionTypeId, "Question type", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.QuestionTypeId, new SelectList(ViewBag.QuestionTypes, "QuestionTypeId", "Name"), new { #class = "form-control col-md-10" })
<button type="button" class="btn btn-default addAnswer hide"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
#Html.ValidationMessageFor(model => model.QuestionTypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group hide">
#Html.LabelFor(model => model.Answers, "Options", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" id="allAnswers">
#Html.ValidationMessageFor(model => model.Answers, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Sort, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sort, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sort, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Mandatory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Mandatory)
#Html.ValidationMessageFor(model => model.Mandatory, "", new { #class = "text-danger" })
</div>
</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", "Question", "Survey", new { id = Model.SurveyId }, null)
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval", "~/Scripts/QuestionAdd.js")
}
Controller
[HttpGet]
public ActionResult Add(long id)
{
var question = new Models.Question();
question.SurveyId = id;
ViewBag.QuestionTypes = BLL.Questions.GetQuestionTypes();
return View(question);
}
[HttpPost]
public ActionResult Add(FormCollection coll)
{
if (ModelState.IsValid)
{
var question = new Models.Question();
question.Name = coll["Name"];
byte qid = 0, sort = 0;
bool mandatory = false;
byte.TryParse(coll["QuestionTypeId"], out qid);
byte.TryParse(coll["Sort"], out sort);
bool.TryParse(coll["Mandatory"], out mandatory);
question.QuestionTypeId = qid;
question.Sort = sort;
question.Mandatory = mandatory;
foreach (var answer in coll["Answers"])
question.Answers.Add(new Models.Answer() { Value = answer + "" });
if (question != null)
{
if (BLL.Questions.Insert(question) != null)
ViewBag.Message = "Successfully inserted";
else
ViewBag.Message = "Insert could not be done";
return RedirectToAction("Index", "Question", new { questionId = question.QuestionId });
}
}
return View();
}
When (+) clicked
$('#allAnswers').append(
'<div class="input-group col-lg-4">' +
'<input class="form-control" name="Answers"> ' +
'<div class="input-group-btn">' +
' <button type="button" class="btn btn-default removeAnswer"><span class="glyphicon glyphicon glyphicon-trash" aria-hidden="true"></span></button>' +
'</div> </div>');
As discussed.. here is how i would approach this.
I have a view model to hold the questions and answers and the selected question to which we will be adding answers.
public class CurrentViewModel
{
public string QuestionSelected { get; set; }
public List<SelectListItem> Questions { get; set; }
public List<string> Answers { get; set; }
}
Then in your controller we have an action to return the view, an action to get the answers for the selected question, an action to add a new answer for the selected question and also a save method which just demonstrates the final model content posted.
public class TestController : Controller
{
public ActionResult Test()
{
var model = new CurrentViewModel()
{
Questions = new List<SelectListItem>()
{
new SelectListItem()
{
Text = "Question 1",
Value = "Question 1"
},
new SelectListItem()
{
Text = "Question 2",
Value = "Question 2"
}
},
Answers = new List<string>()
};
return View("Test", model);
}
public PartialViewResult GetAnswers(CurrentViewModel model)
{
model.Answers = new List<string>();
//model.Answers = Get Answers from some service based on QuestionSelected?!
model.Answers.Add("Answer 1");
model.Answers.Add("Answer 2"); //Add manuall for example
return PartialView("_Answers", model);
}
public PartialViewResult AddAnswer(CurrentViewModel model)
{
model.Answers.Add("Add answer here...");
return PartialView("_Answers", model);
}
public ActionResult SaveQuestionsAndAnswers(CurrentViewModel model)
{
if (model.Questions.Count == 0)
{
}
return View("Test", model);
}
}
Then we have a main view for showing the questions dropdown and a partial view that will show us the answers.
Main View
#model TestMVC.Models.CurrentViewModel
#{
ViewBag.Title = "Test";
}
<link href="~/Content/StyleSheets/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Scripts/jquery-2.2.3.js"></script>
<script src="~/Content/Scripts/jquery-ui-1.11.4.js"></script>
<div id="divBodyContent">
<div>
<h3>Q & A</h3>
</div>
#using (Html.BeginForm("SaveQuestionsAndAnswers", "Test", FormMethod.Post, new { id = "frmQandA" }))
{
#Html.Label("lblQ", "Questions", new { #class = "form-control inline" })
#Html.DropDownListFor(model => model.QuestionSelected, Model.Questions, "Select--", new { #class = "form-control inline", id="ddQuestions" })
<div id="divAnswers">
#Html.Partial("_Answers")
</div>
<div style="margin-top: 1%;">
<button id="btnSave" type="submit" class="btn btn-primary" style="margin-left: 4px; margin-bottom: 10px; width: 7%">save</button>
</div>
}
</div>
<script>
$("#ddQuestions").on("change", function() {
var myData = $('#frmQandA').serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetAnswers", "Test")",
data: myData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
$("#divAnswers").html(data);
}
})});
</script>
Partial View
#model TestMVC.Models.CurrentViewModel
<link href="~/Content/StyleSheets/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Scripts/jquery-2.2.3.js"></script>
<script src="~/Content/Scripts/jquery-ui-1.11.4.js"></script>
<div>
#for (var counter = 0; counter <= (Model.Answers.Count - 1); counter++)
{
#Html.TextBoxFor(model => model.Answers[counter], new {#class = "form-control inline"})
}
<div style="margin-top: 1%;">
<button id="btnAddAnswer" type="button" class="btn btn-primary" style="margin-left: 4px; margin-bottom: 10px; width: 7%">Add</button>
</div>
</div>
<script>
$("#btnAddAnswer").on("click", function() {
var myData = $('#frmQandA').serialize();
$.ajax({
type: "POST",
url: "#Url.Action("AddAnswer", "Test")",
data: myData,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
$("#divAnswers").html(data);
}
})});
</script>
I've tested this locally and it works. In a nutshell, when we need a new answer adding to the model, we add it in server side so we can then bind to the model in the browser. We do this via an Ajax call on the change event of the questions drop down. The partial view iterates through each answer via a counter which generates a unique id and textbox for each answer. Adding a new answer is also achieved via ajax. These can then all be posted back.
Hope that helps.

Create function not saving data to database

I'm trying to get the create function to have the user selected values entered into the database. When the create button is pushed, no error is thrown but, the data is not populated. I'm pretty sure my frequency fields are causing the issue but have been unable to come with a solution.
There are two different types of frequencies a user can select depending upon their "Notification Name" selection. One selection has 3 separate fields for a numerical value, time frame (week, month etc.), and a before/after selection. The other simply states instantaneous as a static text field. Regardless of which option is chosen the frequency data should be populated into one cell within the database which is then separated using piping where necessary. I'm still pretty new to C# MVC so any help is greatly appreciated.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,notificationType1,recipientTypeId,frequency")] NotificationType notificationType)
{
if (ModelState.IsValid)
{
db.NotificationType.Add(notificationType);
db.SaveChanges();
return RedirectToAction("Create");
}
ViewBag.recipientTypeId = new SelectList(db.RecipientType, "Id", "recipientRole", notificationType.recipientTypeId);
return View(notificationType);
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.notificationType1, "Notification Name", htmlAttributes: new { #class = "control-label col-md-2 helper-format" })
<div class="col-md-10" id="type_selection">
#Html.DropDownList("notificationType1", new List<SelectListItem> {
new SelectListItem { Text = "Make a Selection", Value="" },
new SelectListItem { Text = "Incomplete Documents", Value= "Incomplete Documents" },
new SelectListItem { Text = "All Documents Complete", Value = "All Documents Complete" },
new SelectListItem { Text = "Documents Requiring Action", Value = "Documents Requiring Action" }
}, new { #class = "helper-format", #id = "value_select", style = "font-family: 'Roboto', Sans Serif;" })
#Html.ValidationMessageFor(model => model.notificationType1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="frequency_group">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-3" id="frequency_group">
#Html.TextBoxFor(model => model.frequency, new { #class = "textbox-width", #placeholder = "42" })
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Day(s)", Value= "| Day"},
new SelectListItem { Text = "Week(s)", Value= "| Week"},
new SelectListItem { Text = "Month(s)", Value= "| Month"}
})
#Html.DropDownList("frequency", new List<SelectListItem>
{
new SelectListItem { Text = "Before", Value= "| Before"},
new SelectListItem { Text = "After", Value= "| After"}
})
</div>
<p class="col-sm-2" id="psdatetext">The Beginning</p>
</div>
<div class="form-group" id="freq_instant">
#Html.LabelFor(model => model.frequency, "Frequency", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="instant_text">
<p>Instantaneous</p></div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.recipientTypeId, "Notification For", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("recipientTypeId", new List<SelectListItem>
{
new SelectListItem { Text = "Me", Value= "Me"},
new SelectListItem { Text = "Account Manager", Value="Account Manager" },
new SelectListItem { Text = "Candidate", Value= "Candidate"},
new SelectListItem { Text = "Recruiter", Value="Recruiter" },
new SelectListItem { Text = "Manager", Value= "Manager"}
})
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<div id="hovercreate">
<button type="submit" value="CREATE" class="btn btn-primary" id="createbtn">CREATE</button>
</div>
</div>
</div>
</div>
}
JS for frequency options
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
$('#frequency_group').hide()
$('#freq_instant').hide()
$('#value_select').change(function () {
var selection = $('#value_select').val();
$('#frequency_group').hide();
switch (selection) {
case 'Incomplete Documents':
$('#frequency_group').show();
break;
case 'All Documents Complete':
$('#frequency_group').show();
break;
}
});
$('#value_select').on('change', function () {
if (this.value == 'Documents Requiring Action') {
$("#freq_instant").show();
}
else {
$("#freq_instant").hide();
}
});
});
Have you placed a break-point on the method? And if so, is it triggering?
If not, try this...
From what I remember, all Controllers has a default parameter of ID which is set in the RouteConfig.cs file (App_Start/RouteConfig.cs).
There's a couple of ways to go from there.
1. Give the controller the ID parameter (e.g. (int ID))
2. Set the route value via the Route attribute
To do this you need to -
A. Add the following at the top of your RouteConfig.cs / RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//...
}
B. Add
[ValidateAntiForgeryToken]
[Route(#"Create/")]
public ActionResult Create([Bind(Include = ...
{
I would also suggest putting a break-point at the beginning of the method to see if its hitting it.
http://www.tutorialsteacher.com/mvc/routing-in-mvc
https://msdn.microsoft.com/en-us/library/system.web.mvc.routecollectionattributeroutingextensions.mapmvcattributeroutes%28v=vs.118%29.aspx
Is the Id key manually assigned? If not (for example, if it's an IDENTITY field), you shouldn't be binding it - remove Id from [Bind(Include = "...")].

Passing value from page to Html.ActionLink

My problem is:
I have two fields, and when i call my #Html.Actionlink method it send a null value for these two parameters.
This is my page code:
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
<div class="text-center margin-top15">
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
</div>
</div>
This is my InsertNewSkill method:
public ActionResult InsertNewSkill(int professionalId, string skillDescription, string categoryName)
{
initBusinessObjects();
var professional = professionalBusiness.GetById(professionalId);
var newSkill = new SkillModel { Description = skillDescription, Category = new SkillCategoryModel { Name = categoryName } };
skillBusiness.Insert(newSkill);
professional.Skills.Add(newSkill);
professionalBusiness.Update(professional);
return View();
}
What I must to do to achieve this (send the textbox values)?
Have you tried adding the controllerName to your actionLink?
#Html.ActionLink("Adicionar nova habilidade", "InsertNewSkill","CONTROLLER_NAME", new
{
professionalId = ViewBag.professionalId,
skillDescription = "Test Text",
categoryName = Model.skill.Category.Name
}, new
{
#class = ""
})
Without using jQuery / javascript, you should use a form to get those values back to the server.
#{using(Html.BeginForm("InsertNewSkill", "ControllerName", FormMethod.Get)){
<div id="new-skill" class="row">
<label for="Description">Descreva brevemente a sua habilidade:</label>
#Html.TextBoxFor(model => model.skill.Description, new { #class = "form-control" })
<label for="Name">Em qual categoria ela está?</label>
#Html.TextBoxFor(model => model.skill.Category.Name, new { #class = "form-control" })
#Html.Hidden("professionalId", ViewBag.professionalId)
<div class="text-center margin-top15">
<input type="submit" value="Adicionar nova habilidade"/>
}}
With that said, typically you should POST these values back to the server and then redirect to a new ActionMethod (Thus, the acronym PRG for Post, Redirect, Get).

Categories