Hello I am trying build a comment section for some physics articles in my site and for now i would like that when i click on
<a asp-route-articleid="smth" asp-action="Create">Create New</a>
it creates a page with url: http://localhost:65401/Physics/Create?articleid=smth
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<h4>Physics</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="CommentContext" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="CommentContext" class="form-control" />
<span asp-validation-for="CommentContext" 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>
</form>
and now my question: How would I go about extracting that articleid in my controller? So far i tried this
public async Task<IActionResult> Create([Bind("ID,CommentContext,UserName,ArticleID")] Physics physics, string articleid)
{
if (ModelState.IsValid)
{
physics.UserName = HttpContext.User.Identity.Name;
physics.ArticleID = articleid;
_context.Add(physics);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(physics);
}
and also other desperate attempts by no luck so far. Any help would be appreciated.
EDIT:
using HttpContext.Request.GetEncodedUrl();gets me http://localhost:65401/Physics/Create but the point is I need that articleid=smth value.
Solution:
Request.Headers["Referer"].ToString();
will return string of full url including that 'articleid=smth' value.
If I understand I problem then you have following problem.
You have Create Button on One Page and that generate link you described. http://localhost:65401/Physics/Create?articleid=smth
Now when you click that link Your create method get called and it will return View that you have specified. ( At this time if you look articleId in your method then it will have that value).
Now after you value in comment and you submit the form. At that time You will not able to find articleId. This is because articleId not preserve anywhere.
If above is your issue then following will solve your problem.
Solution.
In Controller create two method
Get Method that will called when you click Create New. Another one is called when you submit the form.
Controller
[HttpGet]
public async Task<IActionResult> Create(string articleId)
{
Physics t = new Physics();
if(!string.IsNullOrEmpty(articleId))
{
t.ArticleID = articleId;
}
return View(t);
}
[HttpPost]
public async Task<IActionResult> Create([Bind("ID,CommentContext,UserName,ArticleID")]Physics physics)
{
if (ModelState.IsValid)
{
physics.UserName = HttpContext.User.Identity.Name;
//_context.Add(physics);
//await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(physics);
}
In your view I have made small change so articleId will preserve. ( See I have created hidden field for articleId)
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<input asp-for="ArticleID" type="hidden" />
<h4>Physics</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="CommentContext" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="CommentContext" class="form-control" />
<span asp-validation-for="CommentContext" 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>
</form>
I hope that this solution will help you.
Related
I am facing the issue of data validation being executed on load of a new page even though it is clearly coming from a Get method. Is there something that's triggering the validations on page load?
I have a button on a view to add a new Student record in the new screen :
View :
<a type="button" id="btnAddStudent" href='#Url.Action("Details","Student")' class="btn btn-tertiary" title="Add Student">Add Student</a>
The controller code for the Details action method in Student Controller is as follows.
[HttpGet]
public ActionResult Details(StudentInfo model)
{
//This is populating the model parameters as expected.
helper.StudentInfo(ref model);
return View(model);
}
The view for the Details screen is as follows. The page loads but is throwing validation errors even though it's a Get method.
<form id="frmSubmit" asp-action="Details" asp-controller="Student" method="post">
<input type="hidden" asp-for="StudentId" />
<div class="row">
<div class="col-xs-12">
#Html.ValidationSummary("", new { #class = "alert alert-danger validation" })
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label asp-for="Name">*StudentName</label><br />
<input asp-for="Name" class="form-control" maxlength="100" placeholder="Enter student name..." />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label asp-for="AddressLine1"></label><br />
<input asp-for="AddressLine1" class="form-control" placeholder="Enter address..." />
<span asp-validation-for="AddressLine1" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label asp-for="AddressLine2"></label><br />
<input asp-for="AddressLine2" class="form-control" maxlength="100" />
<span asp-validation-for="AddressLine2" class="text-danger"></span>
</div>
</div>
</div>
<div class="box">
<div class="form-group pull-right">
<button type="submit" class="btn btn-primary" value="save"> Save</button>
</div>
</div>
Is there something I am doing wrong? I have verified that the debug control goes to the Get method.There's alos no on load scripts which are doing any sort of validation.
1.Your get method contains the model parameter, when the request hit the method it will judge the ModelState by default. And when you hit the get method by your shared <a>, it send request without any data, so the ModelState is invalid.
2.Default Tag helper displays ModelState's value not Model.
In conclusion, you will render the ModelState error although it is a get method.
Two ways you can resolve this problem. The first way is that you can add ModelState.Clear() before you return View:
public ActionResult Details(StudentInfo model)
{
ModelState.Clear(); //add this....
helper.StudentInfo(ref model);
return View(model);
}
The second way is do not add the model as parameter:
public ActionResult Details()
{
var model = new StudentInfo();
helper.StudentInfo(ref model);
return View(model);
}
As the title says, I am wondering how I would go about parsing out multiple lines of text from a single TextBox, but submit each of those values individually to my database.
The users have a display where they enter in a barcode that represents a physical location at the facility, and they can put multiple plants in that location. So instead of having them submit a new form for every single plant, I figured this would be an easier way to do so.
However, I'm struggling to understand HOW to make this happen in my controller on the HttpPost event for Create();
The info that gets passed is: ID, UserId, PlantId, Barcode, Date, and Time. The ID (auto updated) and PlantId would be the only things that change. The Barcode, Date and Time should be the same value. I have removed all my failed attempts in my examples here so you can see how it works WITHOUT what I'm wanting to do.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,PlantId,Barcode,UserId,Date,Time")] VegLocationModel vegLocationModel)
{
if (ModelState.IsValid)
{
_context.Add(vegLocationModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Create));
}
return View(vegLocationModel);
}
View:
#model tester.Models.VegLocationModel
#{
ViewData["Title"] = "Create";
var userName = "TEST";
var currentDate = DateTime.Now.Date.Month.ToString() + "/" + DateTime.Now.Date.Day.ToString() + "/" + DateTime.Now.Date.Year.ToString();
var currentTime = string.Format("{0:hh:mm:ss tt}", DateTime.Now);
Html.Hidden("UserId");
Html.Hidden("Date");
Html.Hidden("Time");
}
<h1>Create</h1>
<h4>VegLocationModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Barcode" class="control-label"></label>
<input asp-for="Barcode" class="form-control" style="min-width:100%"/>
<span asp-validation-for="Barcode" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PlantId" class="control-label"></label>
<textarea asp-for="PlantId" class="form-control" rows="10" cols="50">
</textarea>
<span asp-validation-for="PlantId" class="text-danger"></span>
</div>
<div class="form-group">
<input id="UserId" type="hidden" value="#userName" asp-for="UserId" class="form-control" />
<span asp-validation-for="UserId" class="text-danger"></span>
</div>
<div class="form-group">
<input id="Date" type="hidden" value="#currentDate" asp-for="Date" class="form-control" />
<span asp-validation-for="Date" class="text-danger"></span>
</div>
<div class="form-group">
<input id="Time" type="hidden" value="#currentTime" asp-for="Time" class="form-control" />
<span asp-validation-for="Time" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
the value of your textarea posted to Action "Create" is in type of string not int,so you couldn't bind it with VegLocationModel
you could try as below:
[HttpPost]
public IActionResult Create(SomeTest someTest,string plantid)
{
List<int> plantids = plantid.Split("\r\n").Select(m=>Convert.ToInt32(m)).ToList();
return Ok();
}
the result:
try as below to update your database:
public async Task<IActionResult> Create(SomeTest someTest)
{
List<string> plantids = someTest.PlantId.Split("\r\n").ToList();
var soemtestlist = new List<SomeTest>();
foreach (var id in plantids)
{
soemtestlist.Add(
new SomeTest(){
Barcode= someTest.Barcode,
Time= someTest.Time,
UserId= someTest.UserId,
PlantId = id
});
}
_context.SomeTest.AddRange(soemtestlist);
await _context.SaveChangesAsync();
return Ok();
}
The Result:
In the multiline textbox, the new line can be separated as \r\n (works in windows) OR \n\r depending on the operating system. So, logic is simple. Just split your multiline textbox with either \n\r or \r\n and store it in separate rows in the database.
Somebody good at MVC ASP.NET and C#?. Need a little help.
I'm creating a web application and i want to display a datagrid when clicking on CREATE BUTTON and it should allow me to select 1 or n tuples from that datagrid.
Take a look, i made this image:
How can i do that? I tried different thing but no one really worked :(
This is my code:
CONTEXT FILE:
public void CreateUser (User user)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("Create_user", con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#NAME", user.NAME);
cmd.Parameters.AddWithValue("#LAST", user.LAST);
cmd.Parameters.AddWithValue("#DESCRIPTION", user.DESCRIPTION);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Controller file (only the CREATE method is shown):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, [Bind] User user)
{
try
{
if (ModelState.IsValid)
{
dbContext.UpdateAprobador(user);
return RedirectToAction("Index");
}
return View(dbContext);
}
catch
{
return View();
}
}
My VIEW FILE:
#model WebApplicationNewsan.Models.User
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>User</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="NAME" class="control-label"></label>
<input asp-for="NAME" class="form-control" />
<span asp-validation-for="NAME" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LAST" class="control-label"></label>
<input asp-for="LAST" class="form-control" />
<span asp-validation-for="LAST" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DESCRIPTION" class="control-label"></label>
<input asp-for="DESCRIPTION" class="form-control" />
<span asp-validation-for="DESCRIPTION" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
I'm stuck on this situation and i dont understand how to make it works on MVC ASP.NET Core using C#
I created a viewgrid that allows me to Create, Update, Delete every single row shown in the grid. The problem is that everytime i click on CREATE it shows me a page where i can only write (manually) everything but instead of that i want my application to display another viewgrid (from a different database table) and allow the user to select the ROW or ROWS that he wants to add (something like a checkbox or whatever).
Take a look:
How can i do that?. I searched a lot but nothing really helped at all. Found something related to FORMS but not sure about that
This is my CONTEXT cs file:
public void CreateUser (User user)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("Create_user", con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
cmd.Parameters.AddWithValue("#NAME", user.NAME);
cmd.Parameters.AddWithValue("#LAST", user.LAST);
cmd.Parameters.AddWithValue("#DESCRIPTION", user.DESCRIPTION);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
This is my Controller file:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, [Bind] User user)
{
try
{
if (ModelState.IsValid)
{
dbContext.UpdateAprobador(user);
return RedirectToAction("Index");
}
return View(dbContext);
}
catch
{
return View();
}
}
This is my VIEW file:
#model WebApplicationNewsan.Models.User
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>User</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="NAME" class="control-label"></label>
<input asp-for="NAME" class="form-control" />
<span asp-validation-for="NAME" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LAST" class="control-label"></label>
<input asp-for="LAST" class="form-control" />
<span asp-validation-for="LAST" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DESCRIPTION" class="control-label"></label>
<input asp-for="DESCRIPTION" class="form-control" />
<span asp-validation-for="DESCRIPTION" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
I want pass params from view to controller, but dont know how make it with asp.net tag-helpers. What i make wrong? Params not received on controller.
<form asp-controller="Role" asp-action="Create" asp-route-returnurl="#ViewBag.ReturnUrl" method="post" class="form-horizontal" role="form">
<div class="form-group">
<label asp-for="#Model.Name" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="#Model.Name" class="form-control" />
</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>
</form>
How pass data from inputbox to controller?
[HttpPost]
public ActionResult Create(string rolename)
{
try
{
this.context.Roles.Add(new IdentityRole()
{
Name = rolename
});
this.context.SaveChanges();
}
In your action method change rolename to name. The default model binder doesn't know where to initialize this rolename from. Additionally you can inspect what is posted on the server via fiddler.